How to handle AJAX request on the same page – PHP

AJAX is use to communicate with the server to perform the action without the need to refresh the page.

You can either handle AJAX requests on the same page or on the separate page.

In this tutorial, I show how you can send and receive AJAX requests on the same page.

How to handle AJAX request on the same page - PHP


Contents

  1. AJAX call
  2. Handle Request
  3. Avoid conflict
  4. Example 1
  5. Example 2 (With JSON response)
  6. Conclusion

 

1. AJAX call

You can either specify the URL or not when sending AJAX request.

With URL

$.ajax({
  url: 'ajaxfile.php',
  type: 'post',
  data: {value: value},
  success: function(response){
     // Code
  }
   
});

Without URL

$.ajax({
  type: 'post',
  data: {value: value},
  success: function(response){
    // Code
  }
});

Example

$(document).ready(function(){
 $('#name').keyup(function(){
  var name = $('#name').val();

  $.ajax({
   type: 'post',
   data: {name: name},
   success: function(response){
    $('#response').text('name : ' + response);
   }
  });
 });
});

 

2. Handle Request

Put your PHP code at the top of the page so no HTML execute before and any PHP code echo.

Add exit() method at the end of the AJAX handler.

Example

if( isset($_POST['name']) ){
 echo $_POST['name'];
 exit;
}

 

3. Avoid conflict

If the AJAX variable and form submitted variable are of the same name then there is been always the possibility of conflict.

To solve this issue either change the variable names or pass an extra value with AJAX request that will only initialize when sending AJAX request and check if it is initialized or not.

Example

<?php
// Handle AJAX request (start)
if( isset($_POST['ajax']) && isset($_POST['name']) ){
 echo $_POST['name'];
 exit;
}
// Handle AJAX request (end)
?>
<!-- Script -->
<script>
$(document).ready(function(){
 $('#name').keyup(function(){
  var name = $('#name').val();
 
  $.ajax({
   type: 'post',
   data: {ajax: 1,name: name},
   success: function(response){
    $('#response').text('name: ' + response );
   }
  });
 });
});
</script>

 


 

4. Example 1

<?php
// Handle AJAX request (start)
if( isset($_POST['ajax']) && isset($_POST['name']) ){
 echo $_POST['name'];
 exit;
}
// Handle AJAX request (end)
?>

<!doctype html>
<html>
 
 <body >
 
  <form method='post' action>

   <input type='text' name='name' placeholder='Enter your name' id='name'>
   <input type='submit' value='submit' name='submit'><br>
   <div id='response'></div>
  </form>

  <!-- Script -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    $('#name').keyup(function(){
     var name = $('#name').val();

     $.ajax({
      type: 'post',
      data: {ajax: 1,name: name},
      success: function(response){
       $('#response').text('name : ' + response);
      }
     });
    });
  });
  </script>
 </body>
</html>

Demo

Enter the value in the textbox element.


 

5. Example 2 (With JSON response)

A simple example with JSON response.

<?php

// Handle AJAX request (start)
if( isset($_POST['ajax']) && isset($_POST['checked']) ){
 $checked_arr = $_POST['checked'];

 echo json_encode($checked_arr);
 exit;
}
// Handle AJAX request (end)
?>

<!doctype html>
<html>
 
 <body >
 
  <form method='post' action>
   <input type='checkbox' value='JavaScript' > JavaScript <br/>
   <input type='checkbox' value='PHP' > PHP <br/>
   <input type='checkbox' value='jQuery' > jQuery <br/>
   <input type='checkbox' value='AJAX' > AJAX <br/>
   <input type='button' value='click' id='but'>
   <div id='response'></div>
  </form>

  <!-- Script -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
   $('#but').click(function(){
 
    var checkarr = [];
    $("input[type=checkbox]:checked").each(function(index,element){
     checkarr.push($(element).val());
    });

    if(checkarr.length > 0){
     $.ajax({
      type: 'post',
      data: {ajax: 1,checked: checkarr},
      dataType: 'json',
      success: function(response){
        $('#response').text('response : ' + JSON.stringify(response) );
      }
     });
    }
 
   });
 });
 </script>
 </body>
</html>

Demo

Checked the checkboxes and click the button.


 

6. Conclusion

It better to pass and an extra parameter with AJAX request to avoid any conflict with form variable if you are handling requests on the same page.

Related Post

Spread the love

3 Comments

  1. Abra said:

    Really appreciate the guide, with so much stackoverflow nonsense this was the clearest answer for helping me to get my form working correctly.

    August 6, 2017
    Reply
  2. Vivek Joshi said:

    Nice, clean and elegant. But I am facing one issue, I am receiving the value, using it to query as well, but the HTML elements are not getting displayed. But on console everything is getting displayed as per my requirements but there is no actual display. Would be really great if you could help this out

    November 4, 2017
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *