I was using the jQuery form plugin to process form submission (found here) on my page but now have to switch to using an purely jQuery AJAX based method (without using any the form plugin but I can use jQuery). What would be the best method of achieving this? I'm having difficulty translating it across. What would an ideal solution look like?
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#result',
beforeSubmit: showRequest,
success: showResponse
};
// bind to the form's submit event
$('#booking').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
// alert('About to submit: \n\n' + queryString);
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
2 Answers 2
You can use jQuery's AJAX function for this directly and, you can pass object literals as parameters without using the form elements.
var params = {id : '1234'};
$.ajax({
type: 'GET',
url: url, // action attribute from form element
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
console.log(result);
},
error: errorFunc
});
If you are using the options
variable in only one request you can create it directly in the ajaxSubmit
function.
$(this).ajaxSubmit({
target: '#result',
beforeSubmit: showRequest,
success: showResponse
});
I think this way is more clear since you dont need to know what the variable options
contains.
Other hint would be be careful with HTML DOM ids, they cannot be duplicated. In your case the use of HTML DOM classes would grant more stable code. (although HTML DOM ids have a better performance)