Search code examples
javascriptphpjqueryajaxresponse

Ajax Alert Response from PHP


Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.

I have an ajax Post function I am using to pass data to a php script.

Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.

Here is the Ajax:

    $(function () {
        $('#pseudoForm').on('click', '#submit', function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "psu_output.php",
                data: $('#pseudoForm').serialize(),
                datatype: 'json',
                success: function (response) {
                    if(response.type == 'success') {
                        $('#messages').addClass('alert alert-success').text(response.message);
                    } else {
                        $('#messages').addClass('alert alert-danger').text(response.message);
                    }
                }
            });
            return false;
        });
    });
</script>

And in my php script I used this:

<?php

$success = true;

if($success == true) {
    $output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
    $output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}

die($output);
?>

Solution

  • The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.