W3docs

How to Create a jQuery Ajax Post with PHP

Here, we will share with you how to create a jQuery Ajax post request with PHP. Just check out the examples and choose the one that suits your needs best.

In this short tutorial, we are going to share with you how to create a jQuery Ajax POST request with PHP.

You will also see how to post JSON data with jQuery easily and quickly.

After checking out this tutorial, you will be able to create Ajax POST requests easily. Review the options below to get started.

Let’s start to code.

jQuery Post Form Data with .ajax() Method

Using the <kbd class="highlighted">.ajax()</kbd> method is one of the best solutions for this task. Here is how to create a jQuery POST request using this method:

jquery ajax post php

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery post form data with .ajax() method by codeofaninja.com</title>
    <style>
      div {
        margin: 10px;
      }
    </style>
  </head>
  <body>
    <h1>jQuery post form data with the .ajax() method</h1>
    <div>Filling out and submitting the form below to receive a response.</div>
    <!-- our form -->
    <form id="userForm" action="/form/submit" method="post">
      <div>
        <input type="text" name="firstname" placeholder="Firstname" />
      </div>
      <div>
        <input type="text" name="lastname" placeholder="Lastname" />
      </div>
      <div>
        <input type="email" name="email" placeholder="Email" />
      </div>
      <div>
        <input type="submit" value="Submit" />
      </div>
    </form>
    <!-- where the response will be displayed -->
    <div id="response"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $('#userForm').submit(function() {
          // showing that something is loading
          $('#response').html("<b>Loading response...</b>");
          /*
           * 'post_receiver.php' - where you will be passing the form data
           * $(this).serialize() - for reading form data quickly
           * function(data){... - data includes the response from post_receiver.php
           */
          $.ajax({
              type: 'POST',
              url: 'post_receiver.php',
              data: $(this).serialize()
            })
            .done(function(data) {
              // demonstrate the response
              $('#response').html(data);
            })
            .fail(function() {
              // if posting your form failed
              alert("Posting failed.");
            });
          // to prevent the page from refreshing, return false;
          return false;
        });
      });
    </script>
  </body>
</html>

Server-Side PHP Handling

The examples above send data to post_receiver.php. Here is a minimal PHP script to handle both form-encoded and JSON POST requests:

<?php
// post_receiver.php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if JSON was sent
    if (strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
        $rawInput = file_get_contents('php://input');
        $data = json_decode($rawInput, true);
        // Handle malformed JSON for production readiness
        if (json_last_error() !== JSON_ERROR_NONE) {
            http_response_code(400);
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON payload']);
            exit;
        }
    } else {
        // Handle standard form-encoded data
        $data = $_POST;
    }

    // Process data and return a response
    echo json_encode(['status' => 'success', 'received' => $data]);
} else {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
}
?>

jQuery Post Form Data with .post() Method

The <kbd class="highlighted">.post()</kbd> method is considered a shorthand for the <kbd class="highlighted">.ajax()</kbd> method. Its syntax is more concise. See how to use it correctly:

jquery ajax request with post method

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery post form data using .post() method by codeofaninja.com</title>
    <style>
      div {
        margin: 15px;
      }
    </style>
  </head>
  <body>
    <h1>jQuery post form data using .post() method</h1>
    <div>Filling out and submitting the form below to receive a response.</div>
    <!-- our form -->
    <form id="userForm" action="/form/submit" method="post">
      <div>
        <input type="text" name="firstname" placeholder="Firstname" />
      </div>
      <div>
        <input type="text" name="lastname" placeholder="Lastname" />
      </div>
      <div>
        <input type="email" name="email" placeholder="Email" />
      </div>
      <div>
        <input type="submit" value="Submit" />
      </div>
    </form>
    <!-- where the response will be shown -->
    <div id="response"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $('#userForm').submit(function() {
          // showing that something is loading
          $('#response').html("<b>Loading response...</b>");
          /*
           * 'post_receiver.php' - where you will be passing the form data
           * $(this).serialize() - for reading form data quickly
           * function(data){... - data includes the response from post_receiver.php
           */
          $.post('post_receiver.php', $(this).serialize(), function(data) {
            // demonstrate the response
            $('#response').html(data);
          }).fail(function() {
            // if posting your form fails
            alert("Posting failed.");
          });
          // to prevent the page from refreshing, return false;
          return false;
        });
      });
    </script>
  </body>
</html>

jQuery Post JSON Data with .ajax() Method

As an additional example, here is how to post JSON data. You need to serialize the object to a JSON string and set the correct content type:

jquery post json data with post method

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery post JSON data using .ajax() method by codeofaninja.com</title>
  </head>
  <body>
    <h1>jQuery post JSON data with .ajax() method</h1>
    <div>Click the button below to receive a response.</div>
    <!-- our form -->
    <input type="button" value="Post JSON" id="postJson" />
    <!-- where the response will be shown -->
    <div id="response"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $('#postJson').click(function() {
          // showing that something is loading
          $('#response').html("<b>Loading response...</b>");
          /*
           * 'post_receiver.php' - where you will be passing the JSON data
           * JSON.stringify() - converts the object to a JSON string
           * contentType: 'application/json' - tells the server the payload format
           */
          $.ajax({
            url: 'post_receiver.php',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              user_id: "143",
              username: "ninjazhai",
              website: "https://codeofaninja.com/"
            }),
            dataType: 'json',
            success: function(data) {
              $('#response').html(data);
            },
            error: function() {
              alert("Posting failed.");
            }
          });
        });
      });
    </script>
  </body>
</html>

Why Use jQuery for Ajax Requests?

This tutorial demonstrated several ways of making Ajax POST requests with jQuery. You may ask why use it. The reason is straightforward: it provides simple, concise, and readable code.

About jQuery Ajax Get() and Post() Methods

These methods are used for requesting data from the server using HTTP GET or POST requests.

They are mainly applied for implementing request and response communication between the client and the server.

GET is used for requesting data from a particular resource. POST is used for submitting data to be processed by a particular resource.