jQuery Ajax POST with PHP: An Example
Submitting data from a form to a database often necessitates a form submission, which causes a browser redirect. Using jQuery and Ajax, it is possible to overcome this by capturing form data and submitting it to a PHP script.
jQuery Code:
The jQuery code is as follows:
<form>
// Prevent form submission $("#foo").submit(function(event){ event.preventDefault(); // Serialize form data var serializedData = $("#foo").serialize(); // Ajax request $.ajax({ url: "/form.php", type: "post", data: serializedData, success: function (response) { console.log("Request successful"); }, error: function (error) { console.error("Error:", error); } }); });
PHP Script:
The PHP script (form.php) receives the submitted data:
<?php $bar = isset($_POST['bar']) ? $_POST['bar'] : null; ?>
Usage:
Wrap your JavaScript code in a document-ready handler:
$(document).ready(function(){ // jQuery code });
Remember to sanitize input when working with user-submitted data.
Shorthand with jQuery .post:
$.post('/form.php', serializedData, function(response) { console.log("Response:", response); });
This method can be used with jQuery versions 1.5 and above.
The above is the detailed content of How Can I Use jQuery Ajax POST with PHP to Submit a Form Without Page Redirect?. For more information, please follow other related articles on the PHP Chinese website!