I am trying to send data from a form to a database. Here is the form I am using:
<form name="foo" action="form.php" method="POST" id="foo"> <label for="bar">A bar</label> <input id="bar" name="bar" type="text" value="" /> <input type="submit" value="Send" /> </form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.php)?
To make an Ajax request using jQuery you can do this by the following code.
HTML:
<form id="foo"> <label for="bar">A bar</label> <input id="bar" name="bar" type="text" value="" /> <input type="submit" value="Send" /> </form> <!-- The result of the search will be rendered inside this div --> <div id="result"></div>
JavaScript:
Method 1
/* Get from elements values */ var values = $(this).serialize(); $.ajax({ url: "test.php", type: "post", data: values , success: function (response) { // You will get response from your PHP page (what you echo or print) }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } });
Method 2
/* Attach a submit handler to the form */ $("#foo").submit(function(event) { var ajaxRequest; /* Stop form from submitting normally */ event.preventDefault(); /* Clear result div*/ $("#result").html(''); /* Get from elements values */ var values = $(this).serialize(); /* Send the data using post and put the results in a div. */ /* I am not aborting the previous request, because it's an asynchronous request, meaning once it's sent it's out there. But in case you want to abort it you can do it by abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */ ajaxRequest= $.ajax({ url: "test.php", type: "post", data: values }); /* Request can be aborted by ajaxRequest.abort() */ ajaxRequest.done(function (response, textStatus, jqXHR){ // Show successfully for submit message $("#result").html('Submitted successfully'); }); /* On failure of request this function will be called */ ajaxRequest.fail(function (){ // Show error $("#result").html('There is error while submit'); });
The .success()
, .error()
, and .complete()
callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done()
, .fail()
, and .always()
instead.
MDN: abort()
. If the request has been sent already, this method will abort the request.
So we have successfully send an Ajax request, and now it's time to grab data to server.
PHP
As we make a POST request in an Ajax call (type: "post"
), we can now grab data using either $_REQUEST
or $_POST
:
$bar = $_POST['bar']
You can also see what you get in the POST request by simply either. BTW, make sure that $_POST
is set. Otherwise you will get an error.
var_dump($_POST); // Or print_r($_POST);
And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.
And if you want to return any data back to the page, you can do it by just echoing that data like below.
// 1. Without JSON echo "Hello, this is one" // 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below echo json_encode(array('returned_val' => 'yoho'));
And then you can get it like:
ajaxRequest.done(function (response){ alert(response); });
There are a couple of shorthand methods. You can use the below code. It does the same work.
var ajaxRequest= $.post("test.php", values, function(data) { alert(data); }) .fail(function() { alert("error"); }) .always(function() { alert("finished"); });
Basic usage of .ajax
would look something like this:
HTML:
<form id="foo"> <label for="bar">A bar</label> <input id="bar" name="bar" type="text" value="" /> <input type="submit" value="Send" /> </form>
jQuery:
// Variable to hold request var request; // Bind to the submit event of our form $("#foo").submit(function(event){ // Prevent default posting of form - put here to work in case of errors event.preventDefault(); // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("input, select, button, textarea"); // Serialize the data in the form var serializedData = $form.serialize(); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to /form.php request = $.ajax({ url: "/form.php", type: "post", data: serializedData }); // Callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); });
Note: Since jQuery 1.8, .success()
, .error()
and .complete()
are deprecated in favor of .done()
, .fail()
and .always()
.
Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready()
handler (or use the $()
shorthand).
Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();
PHP (that is, form.php):
// You can access the values posted by jQuery.ajax // through the global variable $_POST, like this: $bar = isset($_POST['bar']) ? $_POST['bar'] : null;
Note: Always sanitize posted data, to prevent injections and other malicious code.
You could also use the shorthand .post
in place of .ajax
in the above JavaScript code:
$.post('/form.php', serializedData, function(response) { // Log the response to the console console.log("Response: "+response); });
Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With