I am trying to return a confirmation JSON object back to my AJAX function. For some reason, even though, the post is successful (200) the error callback function is always called. I am logging the returning JSON to a file for dubgging and it appears correct. I cannot figure out why this is happening. Can someone offer a suggestion?
PHP Controller Action (CI):
public function sendMail()
{
$senderName = trim($_POST['senderName']);
$returnEmail = trim($_POST['returnEmail']);
$message = trim($_POST['message']);
if (valid_email($returnEmail))
{
send_email('email@email.com','Website Email From: '.$senderName, $message);
$success = array('success'=>'Mail Sent');
//Debugging to file
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = json_encode($success);
fwrite($fh, $stringData);
fclose($fh);
echo json_encode($success);
}
else
{
$errorMessage = array('error'=>'Invalid Email Address');
echo json_encode($errorMessage);
}
}
}
JS:
$.ajax({
type: "POST",
url: "http://domain.com/index.php/mail/sendmail",
data: {senderName: senderName, returnEmail: senderAddr, message: message },
dataType: "JSON",
success: function(msg){
console.log(msg);
},
error: function(data){
alert("Something went wrong"); // possible that JSON wasn't returned
}
});
The problem was that I was not using a relative url for a target. I believe the issue was a cross domain scripting problem. I changed the url property to index.php/mail/sendmail and all is well.