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);
开发者_如何学C },
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.
$.ajax({
type: "POST",
url: "index.php/mail/sendmail",
data: {senderName: senderName, returnEmail: senderAddr, message: message },
dataType: "JSON",
success: function(msg){
console.log(msg);
},
error:function (xhr, ajaxOptions, thrownError){
var x = xhr;
var y = ajaxOptions;
var z = thrownError;
}
});
The error
callback takes up to three arguments: the XHR object, an error string, and an optional exception object. Accept the last two as well and they should tell you what's going on.
You may also want to use a debugger like Firebug, Dragonfly, or Chrome's developer tools to see if the request is as successful as you think.
精彩评论