Getting error in Ajax call but JSFiddle

When I run the following code in my JSFiddle:

var data = {
  "webservice_status" : {
    "status" : "SUCCESS",
    "message" : ""
  },
  "fileNamePathList" : [ {
    "fileName" : "employee_file"
  } ]
}

console.log(data.fileNamePathList[0].fileName);

I can see my console log printing the file name properly. However, when I run the following Ajax call :

$.ajax({
        	  
        	   url: fileUrl + "?refDataID=" + refdata,
        	   success : function(data) {              
        	       // alert('Data insife File Name: '+data.fileNamePathList.fileName);
        	            console.log('Data insife File Name: ');
        	               console.log(data);
        	        	console.log(data.fileNamePathList[0].fileName);
        	    },
        	    error : function(request,error)
        	    {
        	        alert("Request: "+JSON.stringify(request));
        	    }
        	   
        	   
        	   
        	   
           });

It prints the same JSON as above with this statement console.log(data);. However, I get TypeError: data.fileNamePathList is undefined error with this console.log(data.fileNamePathList[0].fileName);

What am I doing wrong? Thanks !

I think, data in AJAX response is string.

Thanks. It worked when I did the following : var obj = JSON.parse(data);

https://api.jquery.com/jQuery.ajax/

You should use either setting dataType: json or $.getJSON for response directly in JSON format.

jQuery should already recognize that it’s JSON based on the MIME type, but you can explicitly specify the expected type like so:

$.ajax({
  dataType: 'json',
  // ...
})

This way you don’t get any surprises when the response happens to be parsed already.

Thanks. It started showing data as an object after I explicitly specified the dataType.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.