I have AJAX contact form on my hosting server and mail.php file on different domain (another hosting). I am trying to validate a form with jQuery and send email using AJAX, but when I call php file, it sends email to mail email box, but doesn’t return a ‘success’ message. Instead I get “an empty string”.
I have in js
$.ajax({
type: 'POST',
url: options.url,
data: {subject:options.subject, name:$('#name').val(), email:$('#email').val(), message:$('#message').val()},
success: function(data){
if( data == 'success') {
$('#callback').append(options.recievedMsg);
} else {
$('#callback').append(options.notRecievedMsg);
}
});
And php looks like this
<?php
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "my.email@mail.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );
$senderName = stripcslashes($_POST['name']);
$senderEmail = stripcslashes($_POST['email']);
$message = stripcslashes($_POST['message']);
if ( $senderName && $senderEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
};
echo 'success';
?>
When I check in console ‘data’ value it says (an empty string) and in ajax if function I always get false and notReceived message.
How can I make php file to return ‘success’ that if(data == ‘success’) state would be true? Am I missing sometehing here?
You can’t send an AJAX request to another domain because of the same-origin policy.