Turtel
Turtel

Reputation: 1259

Jquery Ajax response

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

Answers (3)

Awais Qarni
Awais Qarni

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

yaka
yaka

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

Bart Vangeneugden
Bart Vangeneugden

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

Related Questions