How to Handle AJAX request on the Same Page – PHP

AJAX is used 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 a 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 the 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

Here, I passed ajax: 1 from the $.ajax and check if it is isset($_POST['ajax']) or not.

<?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

Send AJAX request when keyup event trigger on the <input type='text' id='name'> where pass the ajax: 1, name: name as data.

<?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 an extra parameter with AJAX request to avoid any conflict with <form> variable if you are handling requests on the same page and add exit; or die(); at the end of the AJAX handling script.

This stops adding unnecessary code with the AJAX response.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.