I have a form and want it so that when the user submits it, it does the following:
- Posts the data to a URL with ajax.
- Waits for the script at (1) to finish executing
- Submits the form as normal (to it's URL in the
action
parameter).
I've read the following and am having a hard time making sense of it:
This is what I have, and what I've tried:
<form id="contactUsForm" method="post" action="/email.php">
<input type="text" name="firstName" id="firstName">
<input type="text" name="lastName" id="lastName">
<input type="text" name="email" id="email">
<input type="text" name="phone" id="phone">
<textarea name="comments" id="comments"></textarea>
<input type="submit" id="sendBtn" value="Send">
</form>
So I began by stopping the form submitting as normal:
$("form").submit(function(e) {
e.preventDefault();
This works.
I now want to post 2 fields (firstName
, lastName
to a script called curl.php
) with ajax. I've added this:
var self = this,
firstName = $('#firstName').val(),
lastName = $('#lastName').val()
$.ajax({
type: "POST",
url: "/curl.php",
data: {firstName: firstName, lastName: lastName},
cache: false
}).done(function(result) {
console.log(result);
self.submit();
}).fail(function() {
alert('error');
});
My curl.php
script contains the following - which just outputs the POST data for the 2 fields:
echo 'FirstName: ' . $_POST['firstName'] . '<br>';
echo 'LastName: ' . $_POST['lastName'] . '<br>';
I was expecting this would appear in my console, because console.log(result)
should output the response from curl.php
?
In the Network tab a request is made to curl.php
but there is no response data. The form then submits as expected to email.php
.
I'm unclear whether there's an issue with the way I'm making the ajax call, but am assuming curl.php
isn't actually "finishing" before email.php
is executed?
Please can someone give me some pointers on where I'm going wrong. I've spent a lot of time reading the above links and about Promises, but am seemingly unable to make sense of this!
I understand about ajax being asynchronous. But I don't know how to instruct it to "wait" until curl.php
has finished executing before executing email.php
.