Reputation:
I'm working on my wordpress site contact form that I want to be sent without page refreshing. I've managed to get it working, it sends the mail, but then I thought that what if it doesn't succeed, and added the error function. Now, it calls the error function every time, even if it manages to send the mail. Here's the code for it:
$("#Submit").click(function () {
var dataString = $('#knamecontactform').serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://example.com/form.php",
data: dataString,
dataType: "text",
error: function () {
$('#messagenotsent').fadeIn(400);
},
success: function () {
$('#knamecontactform')[0].reset();
$('#messagesent').fadeIn(400);
}
});
return false;
});
And the submitform.php:
<?php
$to = "[email protected]";
$subject = "Message";
$message =
$_POST['Nimi'] . "\n" .
$_POST['Puhelin'] . "\n" .
$_POST['Sposti'] . "\n" .
$_POST['Tiedot'];
$from = $_POST['Nimi'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo 'Mail sent.';
?>
Upvotes: 6
Views: 9834
Reputation: 308
In addition to what the commenters above mentioned (your original problem was cross domain AJAX) you may want to consider using the newer (introduced in ver 1.5) jQuery deferred way of handling AJAX events since the error: and success: functions will be deprecated in future versions of jQuery. In addition to being more future-proof I also think it lends a nice bit of readability to your code.
Instead of success use .done and instead of error use .fail. See below for an example.
$.ajax({
//all your regular ajax setup stuff except no success: or error:
})
.done( function (data, status) {
//do whatever you want with the return data upon successful return
})
.fail( function (data, status) {
//do whatever you want with the return data upon error
});
For more info, check out the jQuery docs on deferred objects.
Upvotes: 5