Submit Form using jQuery AJAX and PHP without Page Refresh

On 12/28/2017

Hi! In this tutorial we will see how to submit form using jquery ajax and php without page refresh. Web Development enhanced with AJAX increases speed and performance thereby improving the overall user experience. It allows you to update part of a web page without refreshing it completely. Basically, when you submit an html form, the entire page will be refreshed. But by using ajax technique, you can submit the form to the web server without having to reload the page. Instead, the form data will be submitted to the server in the background and can be processed in any way you want.

ajax submit form without page refresh using jquery and php

How to Submit Form using jQuery AJAX and PHP?

The jQuery library provides ajax() method which allows you to submit form without refreshing page. It will send an HTTP request to the web server (here is the php script), which is then processed by the server and sends an http response.

Let's see how to do it.

Step 1) Create a Basic HTML Form

First let's create a simple html form containing some input fields and a submit button.

<form id="myForm">
    <input type="text" name="name" placeholder="Enter your name" required />
    <input type="text" name="email" placeholder="Email ID" required />
    <input type="text" name="city" placeholder="City" required />
    <input type="submit" name="submit" value="Submit Form" />
</form>

Step 2) Add a Placeholder for Server Response

Add a div block next to the form. This will act as a placeholder to display the server response.

<div id="postData"></div>

Step 3) Load jQuery

We'll need jquery library to send ajax call. So load it after all the html components but just before the closing body tag.

<script src="js/jquery-1.10.2.js" type="text/javascript"></script>

Step 4) The AJAX Script

Now it's time to write the ajax script. Add the following script after loading 'jquery.js' file.

<script type="text/javascript">
$(document).ready(function(){
    $('#myForm').submit(function(e){
        e.preventDefault();
        $.ajax({
            url: "get_data.php",
            type: "POST",
            data: $(this).serialize(),
            success: function(data){
                $("#postData").html(data);
            },
            error: function(){
                alert("Form submission failed!");
            }
        });
    });
});
</script>

In the above JS, we have called ajax() function on form submission event. Using preventDefault() will cancel the original event and prevent the page from reloading.

There are several options that you can configure for the ajax() function and I have used some in the example. Here are the details of what they represent,

  • The url specifies the server script to which the http request should be sent.
  • The type defines the type of request to be sent. Here I set it as 'POST' to send HTTP POST request.
  • The data can be string or object and contain the form data.
  • The success function will be executed when the server responds true.
  • And the error function will be triggered if the request fails.

Complete Script: index.html

<html>
    <head>
        <title>AJAX Form Submit without Page Refresh</title>
    </head>
    <body>
    
    <form id="myForm">
        <input type="text" name="name" placeholder="Enter your name" required />
        <input type="text" name="email" placeholder="Email ID" required />
        <input type="text" name="city" placeholder="City" required />
        <input type="submit" name="submit" value="Submit Form" />
    </form>
    
    <div id="postData"></div>
    
    <script src="js/jquery-1.10.2.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $('#myForm').submit(function(e){
            e.preventDefault();
            $.ajax({
                url: "get_data.php",
                type: "POST",
                data: $(this).serialize(),
                success: function(data){
                    $("#postData").html(data);
                },
                error: function(){
                    alert("Form submission failed!");
                }
            });
        });
    });
    </script>
    </body>
</html>

Step 5) Server Script

Finally, you need the php script where the http request should be sent. It receives the submitted form data and you can process it like you want and send back the desired response using 'echo' command.

For this example I have simply encoded the $_POST array to json and sent back to the client, which will then be displayed in the #postData div block we have created in step 2.

get_data.php

<?php
echo json_encode($_POST);
?>

Done! We have the client and server script in place. Now you can run index.html and fill up the form with details and click on 'Submit Form'. You can see that the data you have supplied will be displayed as json string in the web page without the page being refreshed.

Read Also:

Likewise you can submit form without page refresh using ajax and php. Instead of ajax() you can use the jquery's post() method to send http request. We can see about that in some other tutorial later. I hope you find it useful. Please don't forget to share it in social media if you like.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *