Taboo Loco
Taboo Loco

Reputation: 571

Ajax DataType: JSON respond is: OK but No output?

Okay so here is my problem. I have a simple jQuery Ajax request and I can't get is work when I set the DataType to "JSON".

    var form_data = { "id": msg, "token": token };

    $.ajax({
        type: 'POST',
        url: "ajax.php",
        data: form_data,
        dataType: 'json',
        beforeSend:function(){
            // this is where we append a loading image
        },
        success: function(data) { 
            var thing = JSON.parse(data);
            $('.body-item').html(thing.b);
        },
        error: function() {
            alert('error');
        }
    });

This is my ajax file actually. The ajax.php looks like this:

            $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

            $foo = json_encode($arr);
            echo $foo;

When I run the jQuery script, I got a 200:OK response with Firebug, and when I take a look at the response I got the following: {"a":1,"b":2,"c":3,"d":4,"e":5}

However I do NOT get anything showed in the .body-item div, nor if I try with alert().

Also if I run the same code WITHOUT the: dataType: 'json' part, I get everything outputted correctly.

What could be the issue here?

Upvotes: 0

Views: 454

Answers (1)

Barmar
Barmar

Reputation: 781503

When you use dataType: 'json', jQuery calls JSON.parse() and puts the result in data. You shouldn't call it yourself, since data is not a JSON string, it's the parsed object. So just do:

$('body-item').html(data.b);

From the documentation:

"json": Evaluates the response as JSON and returns a JavaScript object.

Upvotes: 2

Related Questions