After building custom jQuery on multiple websites to POST form data to a secondary PHP file for processing, I decided there has to be another way. I wanted to build a JavaScript (jQuery) chunk of code that executes when the document is ready and automatically performs the following functions:
- Put the cursor (focus) in the form’s first input field (if multiple forms on the page, be smart enough to use only the first form).
- Detect all forms and automatically generate the code to POST all of the form elements, via AJAX, to the script defined in the form’s action. Furthermore, use the name of each form field as the key in the POST data.
- Load the results into a div with the id of ‘output’.
- Work for forms that are generated and returned as part of the output (not originally part of the page)
Seems simple enough, right? I thought so too… 4 hours ago. However, I have figured it out! Below you will find a sample form that can be placed on any page. This same page will need to load jQuery and an external JavaScript file, as is shown in the example code below.
<head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script> <script type="text/javascript" src="js/ready.js"></script> </head> <form method='post' action='post.php' name='formname' id='formname'> <fieldset> <legend>Search Amazon for Product</legend> <label for='search'>Search Term(s)</label> <input type='text' id='search' name='search' /> <input type='radio' name='tld' value='com' checked>.com</input> <input type='radio' name='tld' value='co.uk'>.co.uk</input> <input type='checkbox' name='box[]' value='CheckOne' /> <input type='checkbox' name='box[]' value='CheckTwo' /> <input type='checkbox' name='box[]' value='CheckThree' /> <input type='submit' id='submit' name='submit' value='Submit' /> </fieldset> </form> <!-- Results loaded in the below DIV --> <div id='output'></div> |
Here is the contents of the external JavaScript file, ready.js where the magic happens. Note: If you choose to load jQuery at the bottom of your page, fine, but make sure that this file is loaded afterwards.
$(document).ready(function(){ // forms $('form').each(function(findex){ // focus first form, first input if (findex == 0){ $(':input:first',this).focus(); } });//form.each $('input[type=submit]').live('click',function(){ $(this).closest('form').submit(function(){ var url = $(this).attr('action'); // get post values var data = {}; // define data object $(':input',this).each(function(index){ // checkbox if ($(this).attr('type') == 'checkbox'){ if ($(this).is(':checked')){ var key = $(this).attr('name'); // if it hasn't been created yet, define it as an array if (typeof data[key] == 'undefined'){ data[key] = []; } data[key].push($(this).val()); // only happens on CHECKED fields } // radio button }else if($(this).attr('type') == 'radio'){ if ($(this).is(':checked')){ var key = $(this).attr('name'); var val = $(this).val(); data[key] = val; } // all others }else{ // write non-checkbox fields to data var key = $(this).attr('name'); var val = $(this).val(); data[key] = val; } }); // post $.post(url,data, function(html) { $("#output").html(html); }); return false; }); //form.submit });//submit.live });//document.ready |
If you were to try this example by entering ‘hello’ into the search box and then checking the first two checkboxes (CheckOne and CheckTwo), your POST data will look like the following:
[search] => hello [tld] => com [box] => Array ( [0] => CheckOne [1] => CheckTwo ) [submit] => Submit |
Remember, as an added bonus, it uses the jQuery .live() event handler to detect a submission, even on forms that are rendered within the output, without any additional work it checks the DOM for new form submissions and converts them to AJAX posts as well!
Hi thanks for the script it was exactly what i was after and saved me a lot of coding, i did have to alter it to get it to work with the latest jquery as live has been removed also i added a check for Image submit buttons:
$(document).ready(function(){
// forms
$(‘form’).each(function(findex){
// focus first form, first input
if (findex == 0){
$(‘:input:first’,this).focus();
}
});//form.each
$(document).on(‘click’,’input[type=submit],input[type=image]’ ,function(){
$(this).closest(‘form’).submit(function(){
var url = $(this).attr(‘action’)+’&ajax=1′;
// get post values
var data = {}; // define data object
$(‘:input’,this).each(function(index){
// checkbox
if ($(this).attr(‘type’) == ‘checkbox’){
if ($(this).is(‘:checked’)){
var key = $(this).attr(‘name’);
// if it hasn’t been created yet, define it as an array
if (typeof data[key] == ‘undefined’){
data[key] = [];
}
data[key].push($(this).val()); // only happens on CHECKED fields
}
// radio button
}else if($(this).attr(‘type’) == ‘radio’){
if ($(this).is(‘:checked’)){
var key = $(this).attr(‘name’);
var val = $(this).val();
data[key] = val;
}
// all others
}else{
// write non-checkbox fields to data
var key = $(this).attr(‘name’);
var val = $(this).val();
data[key] = val;
}
});
// post
//$.post(url,data, function(html) {
// $(“#aJax”).html(html);
//});
$.post(url, data).done(function(data){$(“#aJax”).html(data);});
//alert(‘ok’);
return false;
}); //form.submit
});//submit.live
});//document.ready