Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.parseJSON on $.ajax - problem on parsing response

I don't know why, but there is a problem I'm encountering with $.parseJSON when making an ajax call, I need to check whether the response contains JSON then continue to parse it with $.parseJSON, if it does not contain any JSON then it will print out the response in an element (which the response will contain some HTML).

I then tested if eval would do anything, which of course it did, but I don't want to use eval for this.

The code I've got:

$.ajax({ 
    url: 'ajax.php',
    success: function(response)
    {
        var msg = $.parseJSON(response);

            //alert(typeof(response)); <-- returns 'string'

            //alert(typeof(msg)); <-- returns 'object'

            //alert(msg.error); <-- this doesn't work at all.

            //eval(response) <-- returns [object Object]

        if(msg.error !== '')
        {
            ajaxWindow.html(msg.error);
        }
        else
        {
            ajaxWindow.html(response).hide().slideDown('slow');
        }
    }
});

So how come it's not able to parse the JSON string? jQuery.parseJSON clearly says:

Takes a well-formed JSON string and returns the resulting JavaScript object.

But nothing is being able to be parsed, is this some kind of error, or perhaps a bug?

EDIT: The JSON:

[{"error":"Error loading template"}]
like image 254
MacMac Avatar asked Feb 27 '11 01:02

MacMac


2 Answers

You have an Array, so you need to access it by the first index.

Instead of:

alert( msg.error );

do:

alert( msg[0].error );
like image 193
user113716 Avatar answered Nov 15 '22 00:11

user113716


Use $.post if possible. It sets the Content-Type to HTML automagicly.

like image 33
JJJollyjim Avatar answered Nov 14 '22 22:11

JJJollyjim