Reputation: 1259
What is the correct way to get a response from a PHP when I do an ajax request using Jquery?
I have this code for Jquery:
$('#quote-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
dateType: 'json',
url: 'mail.php',
success: function(data) {
alert(data.msg);
}
});
return false;
});
And PHP code mail.php
:
// Some mail functions here
$mailSent = @mail($to, $subject, $message, $headers);
$return['msg'] = $mailSent ? 'mail sent' : 'mail failure';
echo json_encode($return);
I tried to alert the reponse alert(data.msg)
but it's saying undefined. Any thoughts?
Upvotes: 3
Views: 1465
Reputation: 18006
First change the spelling of datatype
as mentioned by Kavousi. Then parse your incoming data some thing like this in your response
var response = obj = JSON.parse(data);
alert(response.msg);
Upvotes: 0
Reputation: 914
Apart from other things that I haven't tested, but I just saw that there's a misspell in your ajax options:
dateType: 'json'
Change it to:
dataType: 'json'
Upvotes: 6
Reputation: 3446
Have you tried setting your headers to return JSON? This way jQuery knows you're returning JSON
header('Content-type: application/json');
Upvotes: 0