Ferdinand Fatal Ferdinand Fatal - 4 months ago 24
jQuery Question

Sending a html form 2 times without blocking each other

i want to send a html form in 2 different ways

First i need a jQuery .submit() to send the information to a webservice and directly after that i need to send the form to my database.

Now my Problem is that when i use event.preventDefault(); it always only sends the information to the webservice but not the database.

If i dont use pereventDefault(); it sends the Information to the webservice but out of a race condition it doesnt wait for its success funktion post.done(). The Information goes to the Database but not the my webservice.

jQuery('#sendform').submit(function(event) {
event.preventDefault(); //here comes the problem

var post = jQuery.post(url, {
email: email,
firstname: vorname,
surname: nachname,
origin: origin,
newsletter: newsletter
});

post.done(function(data) {
console.log("webservice-done")
//at this point the data should be send to databdase via send.php
});
});


This is my HTML form:

<section class="formular" id="formular">
<form id="sendform" action="send.php" method="post" enctype="multipart/form-data">
<div class="links">
<input id="idvorname" name="vorname" type="text" placeholder="Vorname*" required/>
<br>
<input id="idnachname" name="nachname" type="text" placeholder="Nachname*" required/>
<br>
<input id="idemail" name="email" type="text" placeholder="E-Mail-Adresse*" required/>
<p>* Pflichtfeld</p>
</div>
<div class="absenden">
<input id="senden" type="submit"/></input>
</div>

</form>


So if i use preventDefault() the post in the jQuery part is done and the data is send to the webservice but not to the database via send.php. If i dont use the preventDefault() the data is not correctly send to my webservice but to my database via send.php.

Is there any possibility to make it send to the webservice like with preventDefault(). and only after this is completed it sends to the database?

Ive already tried to use the jQuery Form plugin but it didnt work either. same error like before. I also tried to use .submit() inside the post.done function but i only ended up in a loop sending infinte data to the webservice.

any help realy appriciated

Answer

This should do it, calling native submit DOM method to avoid jQuery handler submit loop:

jQuery('#sendform').submit(function(event) {
    // to avoid any multiple form submissions
    $(this).find(':submit').prop('disabled', true);       

    event.preventDefault(); 

    var post = jQuery.post(url, {
        email: email,
        firstname: vorname,
        surname: nachname,
        origin: origin,
        newsletter: newsletter
    });

    post.done(function(data) {
        console.log("webservice-done")
        this.submit(); // submit form here
    }.bind(this)); // bind to set relevant context
});