I am posting some data to an action on a controller using the CI framework. The post completed successfully but I would like to return a status to the calling jQuery.post().
Using firebug I can see that the post is completed successfully (200) but I don't see the json that I am returning. How come I am not getting the json returned?
public function sendMail()
{
$senderName = trim($_POST['senderName']);
$returnEmail = trim($_POST['returnEmail']);
$message = trim($_POST['message']);
if (valid_email($returnEmail))
{
send_email('me@my.c开发者_如何学Com','Website Email From: '.$senderName, $message);
$success = array('success'=>'Mail Sent');
echo json_encode($success);
}
else
{
$errorMessage = array('error'=>'Invalid Email Address');
echo json_encode($errorMessage);
}
}
Ajax post
$.post("http://example.com/index.php/mail/sendmail",{senderName: senderName, returnEmail: senderAddr, message: message }, function(data){
if(data.status == "success")
{
alert("mail sent.");
}
else
{
alert("mail failure");
}
});
You can test by using $_GET
instead of $_POST
until you get the desired result. Your code should work unless:
- You haven't loaded the e-mail helper
- You're using an old PHP version which doesn't support
json_*()
- Case sensitive method (
sendMail
, notsendmail
)
I'd also recommend using the following code for your JavaScript as well:
$.ajax({
type: 'POST',
url: "http://mysite.com/index.php/mail/sendmail",
data: {senderName: senderName, returnEmail: senderAddr, message: message},
dataType: "JSON",
success: function(data){
if(typeof data.error == "undefined"){
alert("Mail failure");
}
else{
alert("Mail sent");
}
},
error: function(data){
alert("Something went wrong"); // possible that JSON wasn't returned
}
});
The problem was with the url. I think trying to post to 'http://mysite.com' from my local host was causing cross site scripting security issues.
I changed the url property to something relative and it works great.
$.ajax({
type: 'POST',
url: "index.php/mail/sendmail",
data: {senderName: senderName, returnEmail: senderAddr, message: message},
dataType: "JSON",
success: function(data){
if(typeof data.error == "undefined"){
alert("Mail failure");
}
else{
alert("Mail sent");
}
},
error: function(data){
alert("Something went wrong"); // possible that JSON wasn't returned
}
});
精彩评论