In the dynamic world of web development, creating a seamless, user-friendly experience is a top priority. A crucial aspect of this is enhancing the form submission process for better user engagement. Typically, form submission on websites demands a page reload, leading to a less-than-ideal user experience. However, by integrating PHP and jQuery, you can efficiently bypass this hurdle. This comprehensive guide delves into the nuances of submitting forms without a page refresh, leveraging the power of PHP and jQuery to elevate your website’s user experience.

Advertisement

What is PHP?

PHP, or Hypertext Preprocessor, stands as a cornerstone in server-side scripting languages, primarily tailored for web development. Its ability to craft dynamic and interactive web content, coupled with database integration, makes it an indispensable tool for creating robust, data-centric websites.

What is jQuery?

jQuery, a streamlined and powerful JavaScript library, transforms the way you handle HTML document navigation, event management, and web animations. Its user-friendly API ensures compatibility across various browsers, making it an ideal choice for enhancing website interactivity and functionality.

How Does PHP and jQuery Work Together?

The synergy between PHP and jQuery paves the way for the development of sophisticated web applications. PHP handles server-side data processing and database interactions, while jQuery enriches the client-side experience, enabling dynamic webpage alterations without the need for a full page reload.

At the core of non-refreshing form submissions lies AJAX (Asynchronous JavaScript and XML). AJAX revolutionizes how web pages communicate with servers, allowing for partial web page updates in the background. This means that specific sections of a webpage can be updated independently, without reloading the entire page.

Let’s now explore a simple way to submit a form without page refresh using PHP and jQuery.

Step-by-Step Guide: Implementing Form Submission Without Page Refresh in PHP and jQuery

This guide provides a straightforward approach to implementing form submissions without a page refresh, utilizing the combined capabilities of PHP and jQuery. Enhance your website’s functionality and user satisfaction by mastering this essential web development technique.

Step 1: Create HTML Form

Create a index.html file on your website using following content. This is the main HTML form that will display on the website page. You can simply integrate a form into any website page.


<!DOCTYPE html>
<html>
<head>
    <title>Submit Form without Page Refresh Using PHP/jQuery</title>
    <script src="https://code.jquery.com/jquery-latest.js"></script>
    <script src="js/submit.js"></script>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="form-container">
        <form id="myForm" method="post">
            <div class="form-row">
                <label for="name">Name:</label>
                <input name="name" id="name" type="text" />
            </div>
            <div class="form-row">
                <label for="email">Email:</label>
                <input name="email" id="email" type="text" />
            </div>
            <div class="form-row">
                <label for="phone">Phone No:</label>
                <input name="phone" id="phone" type="text" />
            </div>
            <div class="form-row">
                <label>Gender:</label>
                <input name="gender" type="radio" value="male" id="male"><label for="male">Male</label>
                <input name="gender" type="radio" value="female" id="female"><label for="female">Female</label>
            </div>
            <button type="button" id="submitFormData"  onclick="SubmitFormData();">Submit</button>
        </form>
        <br/>
        Your data will display below..... <br />
        ==============================<br />
        <div id="results">
            <!-- All data will display here  -->
        </div>
    </div>
</body>
</html>

Step 2: Create JavaScript File

Now create a JavaScript page with name submit.js inside js directory using following content. You can optimize this JavaScript by adding the jQuery validations.


function SubmitFormData() {
    var name = $("#name").val();
    var email = $("#email").val();
    var phone = $("#phone").val();
    var gender = $("input[type=radio]:checked").val();
    $.post("submit.php", { name: name, email: email, phone: phone, gender: gender },
    function(data) {
	 $('#results').html(data);
	 $('#myForm')[0].reset();
    });
}

Step 3: PHP Form Processing

Now create a PHP script named submit.php. This script will do all your backed operations. When we submit the web form, This script will get all arguments from the POST. You can customize this script according to your requirement like saving values in the database, Email records to Admin, etc.


<?php
  echo $_POST['name'] ."
"; echo $_POST['email'] ."
"; echo $_POST['phone'] ."
"; echo $_POST['gender'] ."
"; echo "==============================
"; echo "All Data Submitted Successfully!"; ?>

Step 4: Add CSS (Optional)

Here is the optional css file used to decorate above form. You should use your own css to customize form as per your website. Create a style.css file inside css directory and add the following content:


body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}
.form-container {
    text-align: left;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 5px;
}
.form-row {
    margin-bottom: 10px;
}
label {
    display: block;
    margin-bottom: 5px;
}
.form-row input[type="text"],
.form-row input[type="radio"],
.form-row label {
    display: inline-block;
    margin-right: 10px;
}
#submitFormData {
    margin-top: 10px;
}

Step 5: Testing

Now access index.html page on web browser and test this example. You can also view this demo.

Conclusion

That's it! You've now successfully created a form that submits without refreshing the page. This technique can significantly streamline UX by providing users with a smoother, faster response to their form submissions. With some practice, you can easily implement this PHP/jQuery strategy in more complex applications, contributing to an efficient and user-friendly web development landscape.

Share.

21 Comments

  1. Thanks so much Rahul! This is something I could build on.
    But I have the same question as above: Is this Ajax? If not, why use Ajax:

  2. Thanks for this! However, I noticed that if i have 2 input radio, instead of 1 as in your demo, it will echo the 1st one it finds twice. How to edit the script so any subsequent radio inputs are trewated seperatly ?

    Thanks!

  3. This work perfect except that the page refreshed when I pressed ENTER.

    After a while I found the function preventDefault(); in javascript. Just want to share this to future users reading the article.

    I solved it like this:

    function enterKey (){
    if (event.key == “Enter”){
    event.preventDefault();
    SubmitFormData();
    }
    }

    • Michael,

      Thanks for posting. I’m new to javascript. This article is really helping me out. I am also having he ENTER issue. Can you somehow incorporate your solution into the syntax of the article?

      function enterKey (){
      if (event.key == “Enter”){
      event.preventDefault();
      SubmitFormData();
      }
      }

      inside or outside the javascript in the article? I don’t know where to put it. Thanks!

      Rahul, this is awesome!

  4. When i try to submit hours in the form, it does not display using this method. However, using the traditional submit method, the hours do show up when being echo. Any advise?

  5. Hello! You can use our professional web design services to improve your online business and website conversions. 8+ years of successful work, reasonable pricing. Please, confirm the request to find out more.

  6. Hi Rahul, This is a great tutorial on the web for newbies like me. However, in my PHP application I have a PHP page with multiple forms. Data submitted on one form generates data elements from the backend MySQL database to be used by another form on the same page. If the submit.php is a different page, how can I get the data elements accessible on the original page? Using $_SESSION or $_COOKIE variables is possible of course but since there are a large number of these data elements, I was wondering if there is a more elegant way of achieving the same result. No page refresh onsubmit and yet result of one form being accsssible to the second form on the same PHP page.

    Thanks a lot in advance.

  7. Hi,
    is it possible to add a file upload to the form and to specify the location where it should be stored on the server?

  8. Php Professional on

    Great tutorial. This tutorial was really helpful to create a submit form without page refreshing on my business site. Its helpful to beginners.Thanks.

  9. Hello,

    Thanks for the great tutorial. In Item #3 you are missing the ending semi-colon. “;”.

    Current:
    echo “All Data Submitted Successfully!”
    Should Be:
    echo “All Data Submitted Successfully!”;

Exit mobile version