java - Is it possible to submit a form and send an ajax request at the same time jquery -
i'd submit form and, @ same time, send ajax request spring mvc server. have form this:
<form id='confirma' method='post' action='confirma'> <button type='submit' id='save' class='btn btn-success' value='save'>enviar</button> </form>
in server, have 2 methods receive both requests (the ajax request , normal form submission).
// receive form @requestmapping("fromform") public string fromform(model model) { // atb1 values database model.addattribute("atb1", atb1); return "file.jsp"; } // receive ajax @requestmapping("fromajax") public void fromajax(string jsondata) { // deserialize json data , insert on database system.out.println("data received!"); }
my intention receive data ajax request, save in database, , data in form submission method, called, in example, fromform.
i know might crazy i'm doing because have sequence of submit forms , i'd make them independent each other call of them without have passed data form.
i have tried deal using jquery. i've done:
function ajaxrequest() { var jsonarray = new array(); // complete jsonarray array of objects created myself $.ajax({ url: "fromajax", cache: false, contenttype: false, processdata: false, data: json.stringify(jsonarray, null, 4), type: 'post', success: function (data, textstatus, jqxhr) { console.log("success ajax"); return true; }, error: function (xhr, status, error) { console.log("error ajax"); return false; } }); } $(document).on('submit', '#confirma', function(event) { event.preventdefault(); // return method, call jsp page, if ajax // request completed return ajaxrequest(); });
this not working though.. if remove event.preventdefault in form submission, receive form submission on server. if have event.preventdefault call, ajax request hits server.
how can make both of requests hit server?
think of browser's perspective. imagine has fired both xmlhttprequest /fromajax
and regular form submission post /confirma
. imagine server responds post /confirma
first. browser when form submission response contains new html page display, or redirect page - should browser (still pending) xmlhttprequest?
or if @ server's perspective - should happen when server processes request fromform()
method before has received or begin process request fromajax()
method?
if intention to
receive data ajax request, save in database, , data in form submission method
then first send ajax request , when receive response, trigger form submission javascript, these requests happen serially (one after other) rather in parallel.
Comments
Post a Comment