简体   繁体   中英

Submitting the form manually using Ajax

I am trying to call a servlet on form submit using ajax. But it's not hitting the ajax and page reloads. I am triggering form submit manually and after that on that submit function i am calling the ajax method.

 $("#image1").on('change', function(event) { $('#myform').trigger('submit'); alert("button clicked"); // this is submitted $("#myform").submit(function(e) { // this is not happening event.preventDefault(); alert('form clicked'); //var formId=("#myform").submit(); $.ajax({ type: 'GET', // GET or POST or PUT or DELETE // verb url: "/bin/mr/controller?q=iechange", data: $("#myform").serialize(), // type // sent // to // server dataType: 'json', // Expected data format from // server processdata: true, // True or False success: function(data) { // On Successfull alert('call success'); console.log(data); }, error: function(msg) { // When Service call alert('call fail'); // fails } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="myform" > <input name="img" id="image1" type="file" accept="image/*"> </form> 

You need to bind your submit event handler when the page loads.

Currently you are trying to bind it after you have manually triggered the submission… which is too late because the event will have been and gone by then.

Move the code which binds the submit event outside the event handler for the change event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM