6

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"}]
3
  • I've had some weird issues like that before, this worked for me in that scenario msg = jQuery.parseJSON(response); Commented Feb 27, 2011 at 1:35
  • Are you sure ajax.php is in the same directory as the URL from which the request is made? Commented Feb 27, 2011 at 1:35
  • Please post the JSON you're trying to parse. Also what do you get when you try alert(msg)? The typeof gives "object" for a lot of different types. Commented Feb 27, 2011 at 1:36

2 Answers 2

7

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

Instead of:

alert( msg.error );

do:

alert( msg[0].error );
Sign up to request clarification or add additional context in comments.

2 Comments

Ah yes, now I've noticed just right after your answer was posted, [{}] - array object, {} - object. jQuery API docs should have included that in the docs! :P
I have tried to parse {"result":"success","msg":"Success"} in javascript but i got value is undefined when i am printing data.result any solution???
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.