Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form via AJAX in jQuery

Tags:

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?

like image 591
Student Avatar asked Mar 04 '12 18:03

Student


People also ask

Can we submit form using AJAX?

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.

Can we submit form in jQuery?

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" ).

What is AJAX form submission?

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.

What is ajaxForm in jQuery?

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.


1 Answers

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;     }); 
like image 122
adeneo Avatar answered Sep 30 '22 05:09

adeneo