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

I don’t know why, but there is a problem that I encounter $.parseJSON when making an ajax call, I need to check if the response contains JSON and then continue parsing with $.parseJSON if it does not contain JSON, then it will print the response in the element (which the response will contain some HTML).

Then I tested if eval would do something, which of course happened, but I don't want to use eval to do this.

The code I have is:

 $.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 why couldn't he parse the JSON string? jQuery.parseJSON clearly says:

Generates a valid JSON string and returns the resulting JavaScript object.

But nothing can be analyzed, is it some kind of mistake or maybe a mistake?

EDIT: JSON:

 [{"error":"Error loading template"}] 
+6
json jquery parsing
source share
2 answers

You have an array, so you need to access it at the first index.

Instead:

 alert( msg.error ); 

do:

 alert( msg[0].error ); 
+7
source share

Use $ .post if possible. It automatically creates a Content-Type for HTML.

+1
source share

All Articles