A
A
Aljo2021-07-03 08:59:16
AJAX
Aljo, 2021-07-03 08:59:16

Is it possible to write a generic ajax+php form handler?

Hello!

Tell me please. There are 4 different forms on the site:
2 forms with one field: the first has email, the second has phone
and 2 forms: textarea+name, and name+phone

Is it possible to write a simple 1 handler for all forms?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2021-07-03
@aljo222

Here is a primitive example for you.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <title>Document</title>
</head>
<body>
  <div>
    <form action="">
       <input type="text" name="name">
       <input type="text" name="phone">
       <input type="hidden" name="first" value="first">
       <input type="submit" name="first">
    </form>		
  </div>
  <div>
    <form action="">
      <input type="text" name="name">
      <input type="text" name="email">
      <input type="hidden" name="second" value="second">
      <input type="submit" name="second">
    </form>		
  </div> 
  <div>
    <form action="">
      <input type="text" name="name">
      <textarea name="textarea"></textarea>
            <input type="hidden" name="third" value="third">
      <input type="submit" name="third">
    </form>		
  </div>	
<script type="text/javascript">
  $(document).ready(function(){
    $("form").on("submit", function(e){
      e.preventDefault()
      var data = $(this).serialize()
      $.ajax({
        url: 'ajax.php',
        method: 'POST',
        data: data,
        success: function(response){
          console.log(response)
          var answer = jQuery.parseJSON(response);
          if(answer.type === 'success'){
            alert(answer.text)
          }
          if(answer.type === 'error'){
            alert(answer.text)
          }
        } 
      }) 
    })
  })
</script>	
</body>
</html>

<?php
  if(isset($_POST)){

  	if(isset($_POST['first'])){
  		if(!empty($_POST['name'])){
  			$answer = ['type' => 'success', 'text' => 'Отправлена форма First'];
  		}else{
  			$answer = ['type' => 'error', 'text' => 'Заполните поле "name" в форме First'];
  		}	
  	}
  	if(isset($_POST['second'])){
  		$answer = ['type' => 'success', 'text' => 'Отправлена форма Second'];
  	}
  	if(isset($_POST['third'])){
  		$answer = ['type' => 'success', 'text' => 'Отправлена форма Third'];
  	} 
  	echo json_encode($answer);
  }
?>

N
Nadim Zakirov, 2021-07-03
@zkrvndm

On the php side of the handler, take the $_POST array and bypass it with foreach. Inside the loop, already form a notification letter with the fields that came from your form.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question