jQuery Ajax POST example with PHP

In web development, it's common to encounter situations where you need to send data from a form to a server without causing the browser to redirect. With the help of jQuery and Ajax, you can achieve this by capturing the form data and submitting it to a PHP script without refreshing the page. In this article, we'll walk through an example that demonstrates how to accomplish this.

Prerequisites

Before we dive into the details, make sure you have the following:

  • A basic understanding of HTML, JavaScript, jQuery, and PHP.
  • A development environment set up with a web server capable of executing PHP scripts.
  • jQuery library included in your HTML file. You can either download it and host it locally, or use a CDN like the following:
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha384-KyFPmT4pb3xsJjkaWUYWupnMxpBMEX2EMTdAmZ9d7jTUgYSe4wTw0vhc0Z+3jZAw" crossorigin="anonymous"></script>

The HTML Form

Let's start by setting up the HTML form that we want to submit using Ajax. Here is a basic form with a single input field:

<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

The form has a name attribute of "foo" and an action attribute that points to a PHP script named "form.php" which will handle the form data. The method attribute is set to "POST" to ensure the data is sent securely. The form also includes an input field with the id "bar" which is the data we want to send to the server.

The JavaScript/jQuery Code

Now that we have our form set up, let's write the JavaScript/jQuery code to handle the form submission and send the data to the PHP script.

$('form#foo').submit(function(event) {
    // Prevent default form submission
    event.preventDefault();

    // Serialize form data
    var formData = $('form#foo').serialize();

    // Send Ajax request
    $.ajax({
        url: 'form.php',
        type: 'POST',
        data: formData,
        success: function(response) {
            // Handle success response
            console.log(response);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // Handle error response
            console.error(textStatus, errorThrown);
        }
    });
});

In this code snippet, we're using jQuery to select the form with the id "foo" and attaching a submit event listener to it. Inside the event handler function, we first prevent the default form submission behavior using event.preventDefault().

Next, we serialize the form data using the .serialize() method provided by jQuery. This converts the form inputs into a query string format that can be easily sent as part of a POST request.

Then, we use the jQuery.ajax() function to send an Ajax request to the PHP script. The url property specifies the URL of the PHP script that will handle the request. The type property is set to 'POST' to indicate that we want to send the data using the POST method.

The data property is set to the serialized form data we generated earlier. This will be sent as the request payload to the server.

The success property is a callback function that will be executed if the request is successful. In this example, we're simply logging the response to the console. You can modify this function to handle the response in any way you like (e.g. updating the page content).

The error property is a callback function that will be executed if the request fails. Here, we're logging the error message to the console. You can customize this function to handle errors in a more user-friendly way.

The PHP Script

Now that we have our form and JavaScript code set up, let's create the PHP script that will handle the form data and store it in a database.

<?php
// Get the form data
$bar = $_POST['bar'];

// Process the data (e.g. store it in a database)

// Return a response
$response = array('message' => 'Form data submitted successfully');
echo json_encode($response);
?>

In this PHP script, we first retrieve the form data using the $_POST superglobal. The input field with the name "bar" corresponds to the 'bar' key in the $_POST array. You can access and process the form data as needed.

Here, we're simply storing it in a variable named $bar. In a real-world scenario, you would likely perform additional validation and sanitization on the form data before using it.

You can then process the data as needed, such as storing it in a database or performing other business logic.

Finally, we create a response array and use json_encode() to convert it into a JSON string. We echo this response back to the client, which will be received by the success callback function in our JavaScript code.

Putting It All Together

With the HTML form, JavaScript/jQuery code, and PHP script in place, you're now ready to test your solution. Make sure you have a webserver running with PHP support, and open your HTML file in a web browser.

When you submit the form, the JavaScript code will intercept the form submission and send an Ajax request to the PHP script. The PHP script will process the data and return a response back to the client.

You can check the browser console to see the response from the PHP script. If everything is set up correctly, you should see the success message that we defined in the PHP script.

Conclusion

In this article, we explored how to use jQuery and Ajax to submit form data to a PHP script without refreshing the page. We covered everything from setting up the HTML form to writing the JavaScript/jQuery code and creating the PHP script to handle the form data.

This technique allows you to create seamless, interactive web applications that can communicate with the server in the background, without interrupting the user's browsing experience. With the power of jQuery and Ajax, you can take your web development to new heights.

External resources: