user1685794
user1685794

Reputation:

Jquery ajax response error

Here is a partial example of what I am trying to achieve.

I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:

PHP:

$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);

Javascript/jQuery:

var ID = 1
$.ajax({
            type: 'POST',
            url: '/ajax/load.php',
            contentType: "application/json; charset=utf-8",
            datatype: 'json',
            data: {ID: ID},
            beforeSend: function(xhrObj) {
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
            success: function(result) {
                if (result.success) {
                        // do something
                }
        });

The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}

This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..

Upvotes: 0

Views: 354

Answers (3)

iConnor
iConnor

Reputation: 20189

$.ajax({
            type: 'POST',
            url: '/ajax/load.php',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: {ID: ID},
            beforeSend: function(xhrObj) {
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
            success: function(result) {
                if (result.success) {
                        // do something
                }
            } // Maybe your forgot this
        });

in other words - Basic Debugging

Upvotes: 1

MrCode
MrCode

Reputation: 64526

Your error is here:

datatype: 'json',

Javascript is case sensitive and the property is dataType:

dataType: 'json',

Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.

You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.

Upvotes: 2

engvrdr
engvrdr

Reputation: 541

in your PHP page put this on top of the page (you are accepting only json response but probably your response headers content type is text/html

header('Content-type: application/json');

Upvotes: 0

Related Questions