2
\$\begingroup\$

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);
 });
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 30, 2012 at 18:23
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

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
});

Documentation can be found here.

answered Mar 31, 2012 at 1:24
\$\endgroup\$
1
\$\begingroup\$

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)

answered Sep 12, 2016 at 13:12
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.