Ajax posts (or gets) using jQuery is a pretty simple affair, and so I’m not really going into that with this particular post.
Rather, I want to highlight just how easily one can post all of a form’s various values (housed in textboxes, text areas, selects or even radio buttons) to a specific jQuery ajax function call.
So let us examine the working example below:
$.post('form_post_handler_script.php',$('#yourform').find(":input").serializeArray(),function (data, textStatus){ alert(textStatus); });
As you can see, we are using the nifty jQuery deprecated $.post() function to handle the actual POST push. The first parameter passed to it is the actual processing page the function needs to push the data to. The last parameter is simply the callback function, which is in this case doing nothing other than alerting the result of the ajax call). That leaves the interesting one, the actual data parameter that currently sits slap bang in the middle of that function call.
We can break down what is happening into three steps. Remember the $.post function expects data to be fed to it in the JSON format, which if you look around at examples on the web, is most often simply scripted by hand. However, this time around we’re going to let jQuery do the work for us!
The first part is the initial location of the form object, this time selected using its unique ID, in other words $(‘#yourform’) where yourform is the id of the form. Then we chain on a find(‘:input’) command that grabs all elements obeying the :input selector found within the initial object result. Finally, these are then converted to JSON format using the nifty serializeArray function, in other words completing the initial task of providing the post function with the data in the format it so craves.
And that’s it. Populating your ajax post push with your form’s values couldn’t get any simpler if it tried! :)
You might also enjoy:
-
Multi-select boxes are wonderful creatures in that they provide a particularly easy to implement user interface element that provides a great deal of functi ...
-
The well-established javascript library jQuery comes bundled with a neat little function that handles loading remote content directly into the current page' ...
-
If you are using the brilliant jQuery DataTables plugin to present your data in nifty dynamic tables, and are using it in a server-side loading context, you ...
-
To iterate though a web form's contents using jQuery is as easy as 123. First, make use of the $(':input') selector and force it to grab the contents of a p ...
-
While working with jQuery and performing AJAX-driven gets and general content loading, have you ever come across your scripts throwing the following error? ...