I am using following jQuery code to submit a form via AJAX.
jQuery('form.AjaxForm').submit( function() { $.ajax({ url : $(this).attr('action'), type : $(this).attr('method'), dataType: 'json', data : $(this).serialize(), success : function( data ) { alert('Submitted') }, error : function( xhr, err ) { alert(''Error); } }); return false; });
Code is working perfectly with no ajax. But does not work if I load form via ajax. I think it is because of loading form via ajax after JavaScript load.
Any solution?
We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.
Answer: Use the jQuery submit() Method You can use the submit() method to submit an HTML form (i.e. <form> ) using jQuery. The jQuery code in the following example will submit the form on click of the button (i.e. the <button> element) which has the type attribute set to button (i.e. type="button" ).
AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.
If using jQuery 1.7+ you could try using .on() to delegate the event and bind to all future forms with the same class. Try finding the closest parent that is not inserted dynamicly instead of $(document).
$(document).on('submit', 'form.AjaxForm', function() { $.ajax({ url : $(this).attr('action'), type : $(this).attr('method'), dataType: 'json', data : $(this).serialize(), success : function( data ) { alert('Submitted'); }, error : function( xhr, err ) { alert('Error'); } }); return false; });
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