I'm looking for most elegant way to ajaxify my forms (with jQuery).
How do you do this?
Here is my solution (I think it is a Progressive enhancement solution), using only jQuery without any plugins:
var form = $('form#YourFormId');
$(':submit', form).click(function (event) {
event.preventDefault();
$.post(form.attr('action'), form.serialize(),
function(data, status) {
if(status == 'success') {
// your code here
}
}
);
});
UPDATED:
If your POST response is "HTML with form" then try this:
function ajaxifyForm(form) {
$(':submit', form).click(function (event) {
event.preventDefault();
$.post(form.attr('action'), form.serialize(),
function(data, status) {
if(status == 'success') {
var newForm = $(data);
ajaxifyForm(newForm);
form.after(newForm).remove();
}
}
);
});
}
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