HTML.form.guide

How to submit a form without reloading the page using PHP

html5 form submit form

PHP is a server-side scripting language. You can’t use PHP to affect the behaviour on the client side (browser). To handle form submission on the client side, you need Javascript.

Here is how you can submit a form without refreshing the page:

  • Handle the form “submit” event using a bit of Javascript code. The form “submit” event is fired by the browser when the user clicks the submit button in the form.
  • In the event handler, collect the form data and post the form data to the server-side PHP script
  • collect the response from the PHP script. Determine whether there was an error.
  • Display the response on the page by modifying the HTML elements on the page.

Here is the HTML code for a sample form (uses bootstrap CSS framework):

<div class="m-1" id="form_container">
<h1>Contact Us</h1>
<div class="fs-6 fw-light mb-2" >Post your message below. We will get back to you ASAP</div>
<form id="contact_form" name="contact_form" method="post">
    <div class="mb-5">
        <label for="message">Message</label>
        <textarea class="form-control" id="message" name="message" rows="5"></textarea>
    </div>
    <div class="mb-5 row">
        <div class="col">
            <label>Your Name:</label>
            <input type="text" required maxlength="50" class="form-control" id="name" name="name">
        </div>
        <div class="col">
            <label for="email_addr">Your Email:</label>
            <input type="email" required maxlength="50" class="form-control" id="email_addr" name="email"
                placeholder="name@example.com">
        </div>
    </div>
    <div class="d-grid">
    <button type="submit" class="btn btn-success">Post</button>
    </div>
</form>
</div>

Here is the code that handles the form submission event:

const form = document.getElementById('contact_form');

form.addEventListener('submit', (event) => {
  event.preventDefault(); // Prevents the default form submission behavior

  // Perform any form validation or data manipulation here

  const formData = new FormData(form); // Create a FormData object with the form data

  fetch("https://example-website.com/form-handler.php", {
    method: 'POST',
    body: formData
  })
  .then(response => {
    if (response.ok) {
      // Handle the successful response
    } else {
      // Handle the error
    }
  })
  .catch(error => {
    // Handle the error
  });
});

Here, “https://example-website.com/form-handler.php" is the URL of your form submission handler PHP script. You can find one sample script here.

Now, once we have received the response from the script, we have to update the page by modifying the contents of the container div.

To replace part of an HTML page using JavaScript, you can use the innerHTML property to replace the content of an element with new HTML code. Here’s some sample code:

const myDiv = document.getElementById('form_container');
myDiv.innerHTML = '<p>Form submitted successfully!</p>';

In this code, we first use document.getElementById() to select the element with the ID “form_container”. We then set the innerHTML property of this element to a new HTML string, which replaces the original content with new content.

Note that setting the innerHTML property in this way will completely replace the content of the selected element. If you want to add new content to an element without replacing the existing content, you can use the insertAdjacentHTML() method instead. Here’s an example:

const myDiv = document.getElementById('form_container');
myDiv.insertAdjacentHTML('beforeend', '<p>Form was submitted successfully!</p>');

In this code, we again select the “myDiv” element using document.getElementById(). We then use the insertAdjacentHTML() method to add new HTML code to the end of the existing content, without replacing it. The first argument to insertAdjacentHTML() specifies the position where the new HTML should be inserted (“beforebegin”, “afterbegin”, “beforeend”, or “afterend”), and the second argument is the HTML code to be inserted.

Here is the updated code:

const form = document.getElementById('contact_form');

form.addEventListener('submit', (event) => {
  event.preventDefault(); // Prevents the default form submission behavior

  // Perform any form validation or data manipulation here

  const formData = new FormData(form); // Create a FormData object with the form data

  const myDiv = document.getElementById('form_container');
  fetch("https://example-website.com/form-handler.php", {
    method: 'POST',
    body: formData
  })
  .then(response => {
    if (response.ok) {
      myDiv.innerHTML = '<p>Form submitted successfully!</p>';

    } else {
      myDiv.innerHTML = '<p>There was an error submitting the form</p>';
    }
  })
  .catch(error => {
    myDiv.innerHTML = '<p>There was an error submitting the form:'+error+'</p>';
  });
});

See Also