How to get Ajax data in PHP on same page

To get Ajax data in PHP on the same page, you can do the following:

  1. Create an HTML form with an input field that will be used to send data to the server.
  2. Create a PHP script that will handle the data sent by the form and return a response to the client.
  3. Create a Javascript function that will use Ajax to send the form data to the server and handle the response.

Here's an example implementation:

<!-- HTML form -->
<form id="myForm">
  <input type="text" name="myData">
  <button type="submit" id="submitBtn">Submit</button>

</form>

<!-- Javascript code using jQuery -->
<script>
$(function() {
  $('#myForm').submit(function(e) {
    e.preventDefault(); // prevent form from submitting normally
    var formData = $(this).serialize(); // get form data
    $.ajax({
      url: 'myPhpScript.php',
      type: 'POST',
      data: formData,
      success: function(response) {
        // handle response from server
        console.log(response);
      }
    });
  });
});

</script>

<!-- PHP script (myPhpScript.php) -->
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $myData = $_POST['myData'];
  // do something with $myData
  // return response to client
  echo 'Data received: ' . $myData;
}

?>

In this example, when the form is submitted, the `submit()` function is called, which prevents the form from submitting normally and sends the form data to the PHP script using Ajax. The PHP script receives the data sent by the form using the `$_POST` superglobal array, processes the data, and returns a response to the client. The response is then handled by the `success` function in the Ajax call and logged to the console.

Previous Post Next Post