Explain Codes LogoExplain Codes Logo

Submit form without page reloading

javascript
form-data-api
javascript-performance
ajax-alternatives
Anton ShumikhinbyAnton Shumikhin·Aug 21, 2024
TLDR

To submit a form without page reload, use AJAX and the fetch() method:

document.querySelector('form').onsubmit = async e => { e.preventDefault(); // "Don't let the form spill the beans!" let response = await fetch('submit.php', { method: 'POST', body: new FormData(e.target) // package the beans (form data) }); let result = await response.text(); console.log(result); // "The beans have been delivered" };

Swap 'submit.php' with your server-side script's URL. Data gets sent asynchronously, resulting in no page refresh.

Going incognito with Iframes

If you are dealing with a non-AJAX environment, an iframe serves as your undercover agent:

  • Draft up an iframe, assign it a unique name, and keep it hidden under the dark shades of display: none.
  • In your form, set the target attribute to the iframe's name. This pits the iframe against the form submission response, winning the fight against page reload.
  • Set your form's action to the PHP element that processes and delivers your form submission to the server.
  • Maintain the POST method for secure and efficient data submission.
<iframe name="hidden_frame" id="hidden_frame" style="display: none;"></iframe> <form action="submit.php" method="post" target="hidden_frame"> <!-- every spy needs a mission. This one's got form fields--> </form>

Pagination without AJAX

FormData API pulls off an amazing performance for those whose hearts do not beat for AJAX. It is a slick act that:

  • Performs the tricky balancing act of modern browser capabilities and a no AJAX environment.
  • Takes the stage with JavaScript and creates a FormData instance from a form element.
let formData = new FormData(document.querySelector('form')); // Additional JavaScript to handle submission without AJAX goes here

Providing feedback: A JavaScript way

Nothing like an appreciative audience. Here's how JavaScript handles the applause:

function notify(message) { // A standing ovation for form submission! console.log(message); }

Combine it with the iframe act for a unifying performance:

document.getElementById('hidden_frame').onload = function() { // The show was a hit! Time for a standing ovation notify('Bravo form, you've been successfully delivered!'); };

Trading off: Know your actors

  • The iframe method is a minimalistic script that lacks in direct client-server chat.
  • Fetch() with FormData has an impressive portfolio with easy handling of multipart form data.
  • Never forget your security guards while scripting server-side (submit.php).

Optimizations and quirky tips

Juggling success and error handling

Regardless of your choice of method, form juggling can be a tad tricky. But a graceful error handling can save the day:

fetch('submit.php', { method: 'POST', body: new FormData(document.querySelector('form')) }).then(response => { if (!response.ok) { throw new Error('Watch out, pile of beans on the way! (Network response was not ok)'); } return response.text(); }).then(text => { console.log('Form juggled successfully with the beans making it to the bowl:', text); }).catch(error => { console.error('We have some spilled beans on the stage:', error); });

Performance and caching

With AJAX, a no-cache magic spell (setting cache:false) maintains a fresh server chat on each form act:

$.ajax({ url: 'submit.php', type: 'POST', data: new FormData($('form')[0]), cache: false, contentType: false, processData: false, success: function(data) { console.log(data); // "That's a wrap, folks!" } });

The after-show cleanup routine

For our iframe act, an after-show cleanup leaves the stage (page) sparkly clean:

let iframe = document.getElementById('hidden_frame'); iframe.onload = function() { // "Curtains down, time for cleanup!" iframe.parentNode.removeChild(iframe); };