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.

31 thoughts on “How to Handle AJAX request on the Same Page – PHP”

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

    Reply
  2. 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

    Reply
  3. I’m writing a PHP plugin so I need all my code to be self-contained, but it looks like I can’t pass my data with ajax because my PHP code executes BEFORE the ajax request gets sent. In your example, the ajax request executes when the keyup() is called, I am trying to get an ajax request automatically, without requiring any user input. Is this possible?

    Reply
    • Hi Nick,
      Yes, it is possible to send AJAX request without user interaction with setInterval and setTimeout functions. With this function, you can send request at regular interval.

      In the example, I am sending AJAX request only when keyup event triggers. You can do the same with any other events – change, keydown, click, focus, etc.

      Reply
  4. I have a question about using the carriage return, or the ‘exit;’ line in your code. If I remove that line, a bunch of code gets printed out on the page. Why is that? Does it have anything to do with how specifically the ‘data’ or the ‘response’ can be handled? Sorry I’m new to PHP and ajax

    Reply
    • When handling AJAX request on the same page then it is necessary to add exit() method at the end of if statement to return response.

      If you do not add exit() then it will continue to execute to the bottom of the page and the unnecessary code added to the response.

      Reply
  5. Hi Yogesh,
    Its really very helpful
    In Last Demo You have given ,for Checkbox
    I have copied same code in my php
    But it doesn’t get success response

    It,s failure message shows following error

    SyntaxError: JSON.parse: unexpected character at line 15 column 1 of the JSON data

    Please help me on this issue

    Warm Regards,
    SandeepG

    Reply
  6. Hi Yogesh,
    The post was great.
    I have one question.
    I want to submit a from with 3 fields first_name, last_name and age.
    How to pass those in data property in $.ajax?
    How to access them individually from response? so that I can use them further.
    I’m trying for a long time but could’t figure it out.
    Could you please help me out!!!

    Thank you.
    sai

    Reply
    • Hi Sai,
      You can pass it as data: {ajax:1,first_name: first_name,last_name:last_name,age: age} in $.ajax. In the PHP script read as –

      if( isset($_POST[‘ajax’]) ){
      $first_name = $_POST[‘first_name’];
      $last_name = $_POST[‘last_name’];
      $age = $_POST[‘age’];
      exit;
      }

      Reply
  7. Hi Yogesh,
    Thank you for the reply. It worked!.
    Could you please show a way to achieve the same using JSON.
    Thank you again!
    Sai

    Reply
    • If you want to return JSON response from AJAX and read it on success then in the PHP script initialize array with the values –
      $return_arr = array(“first_name”=>$_POST[‘first_name’],”last_name”=>$_POST[‘last_name’],”age”=>$_POST[‘age’]);
      echo json_encode($return_arr); exit();

      Now in the $.ajax set dataType: ‘json’ and in success handle the response –

      var first_name = response.first_name; var last_name = response.last_name; var age = response.age;

      Reply
      • Hi Yogesh,
        Thank you so much for the clear explanation.
        I got full idea of this now.
        Have a great day!!!

  8. I hope you are still monitoring this? I don’t want to use click to button up! I have several other js script on the page. When one of the other functions are called(entered), I would like to call/ initiate your code. Can it be done? This was a very good article, thank you for it. And thank you in advance for your answer.

    Reply
  9. Hi Yogesh,
    thanks for the apt solution.
    But I’ve run into a problem with the following use case:-my data (id) is passed via ajax (which resides in ‘page1.php’) to ‘page2.php’. At page2.php, I’m able to echo the id I passed using $_POST[‘id’]. Perfect till now.
    Now starts the real problem: page2.php has a javascript function for displaying charts and this function is called from the page (html) – ‘page1.php’; and I want to pass the ajax data inside that function in page2.php so that I can display the chart using that id.
    I tried using but no luck. Need your help

    Reply
  10. This has been really useful, but how do I output the response out as PHP again?

    I want it to be $user_id = response;

    I’ve tried $_POST and echo etc. but still not success

    Reply
  11. Hi,

    I am wondering how I can actually use my new php variable created from the POST?

    When i go to use it in the middle of my PHP I get the error ‘undefined variable’.

    Thanks

    Reply

Leave a Comment