Home >Web Front-end >JS Tutorial >How to Submit Form Data Without Page Refresh Using jQuery and PHP?
Submitting Form Data via Ajax with jQuery and PHP (form.php)
To prevent browser redirection when submitting forms, you can leverage jQuery and Ajax. Here's how to achieve this for a form like the one provided:
<form>
jQuery:
$(document).ready(function () { $('#foo').submit(function (event) { event.preventDefault(); var $form = $(this); var $inputs = $form.find('input, select, button, textarea'); var serializedData = $form.serialize(); $inputs.prop('disabled', true); $.ajax({ url: '/form.php', type: 'post', data: serializedData, done: function (response) { console.log('Hooray, it worked!'); }, fail: function (jqXHR, textStatus, errorThrown) { console.error( 'The following error occurred: ' + textStatus, errorThrown ); }, always: function () { $inputs.prop('disabled', false); } }); }); });
PHP (form.php):
// Access posted data through $_POST $bar = isset($_POST['bar']) ? $_POST['bar'] : null;
You can also use the shorthand .post instead of .ajax in jQuery:
$.post('/form.php', serializedData, function (response) { console.log('Response: ' + response); });
Tips:
The above is the detailed content of How to Submit Form Data Without Page Refresh Using jQuery and PHP?. For more information, please follow other related articles on the PHP Chinese website!