Asked 3 years ago
17 Jun 2021
Views 598
Chasity

Chasity posted

jQuery Ajax POST example with PHP

jQuery Ajax POST example with PHP
sec8

sec8
answered Apr 28 '23 00:00

jQuery AJAX to send a POST request to a PHP script:

HTML form:



<form id="myForm">
  <input type="text" name="name">
  <input type="email" name="email">
  <button type="submit">Submit</button>
</form>

jQuery AJAX code:



$(document).ready(function() {
  $('#myForm').submit(function(event) {
    // Prevent default form submission action
    event.preventDefault();
    
    // Get form data
    var formData = $(this).serialize();
    
    // Send AJAX request
    $.ajax({
      url: 'process.php',
      type: 'POST',
      data: formData,
      success: function(response) {
        // Handle success response
        console.log(response);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // Handle error response
        console.log(textStatus, errorThrown);
      }
    });
  });
});

PHP script (process.php):



<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Get form data
  $name = $_POST['name'];
  $email = $_POST['email'];
  
  // Process form data
  // ...
  
  // Send response
  echo 'Form submitted successfully!';
}

In this example, when the form is submitted, the submit event is intercepted using jQuery and prevented from performing the default form submission action. The form data is then serialized using the serialize method and sent to the server using a jQuery AJAX request. The url option specifies the URL of the PHP script that will handle the request, and the type option specifies that the request should be sent using the POST method. The success and error options specify callback functions to handle the server's response.

In the PHP script, the form data is retrieved using the $_POST superglobal, and any processing or validation is performed as necessary. Finally, a response is sent back to the client using the echo statement.

Note that you should always validate and sanitize user input before using it in your PHP script to prevent security vulnerabilities.
Post Answer