Reputation: 706
Right now my website opens up and the user can select what they want to order. When they want to submit a order i just want to send an email but the email isn't coming through and my page just restarts.
javascript/AJAX:
<script type="text/javascript">
$(document).ready(
function() {
$('#wholesaleOrderForm').submit(
function() {
if (validateForm()) {
$.post("wholesale_form.php",
$('#wholesaleOrderForm').serialize(),
function(response) {
alert('response = ' + response);
if (response == "success") {
$('#ajax-msg').html("Thanks for subscribing!");
$('#ajax-msg').style.color = "green";
$('#ajax-msg').hide(5000);
} else {
$('#ajax-msg').html("Sorry, there is some error. Please try again.");
$('#ajax-msg').style.color = "red";
$('#ajax-msg').hide(5000);
}
}
);
// prevent postback
return false;
} else {
return false;
}
}
);
}
);
</script>
PHP code:
<?php
$to = "[email protected]";
$subject = 'hello';
$message = "Hello!!";
$headers = 'From: DoNotReply@COMPANY_EMAIL.com';
mail($to, $subject, $message, $headers);
?>
Upvotes: 2
Views: 52
Reputation: 40038
Further to Julaine's suggestion, change these two lines:
$('#wholesaleOrderForm').submit(
function() {
to this:
$('#wholesaleOrderForm').submit(
function(e) {
e.preventDefault();
//rest of your code
Explanation:
Forms submit by navigating to another page (usually specified in an action="newpage.php"
attribute of the form tag. Your AJAX code would not have time to complete before the page navigates away. *Note that if an action=
attribute is not specified, the page just refreshes -- same problem for AJAX.
Further suggestions if that doesn't work:
(1) Divide and conquer. Greatly reduce your code until it works, then gradually add the rest back in, fixing the errors as you find them.
(2) Reduce the ajax to its minimum:
$('#wholesaleOrderForm').submit(function(e) {
e.preventDefault();
$.post("wholesale_form.php", function(response) {
alert(response);
});
});
wholesale_form.php
<?php
echo 'Ajax is working';
Upvotes: 2
Reputation: 15
You need to disable the form's default action with event.preventDefault();
Upvotes: 2