Get JSON object from AJAX call

I am new to AJAX and javascript . In my project, I have to get the json object in my javascript file. I used spray-json and it shows me the json object in the url. http://localhost:8081/all-modules

 { "status": "S1000", "description": "Success", "results": ["module1", "module2", "module3"] } 

My Ajax call

  $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ alert(data) }, success: function(data){ alert(data) } 

It returns a warning [object Object] . What is the problem?

+8
json javascript jquery ajax
source share
7 answers

Try the following:

 var data = '{"name": "John","age": 30}'; var json = JSON.parse(data); alert(json["name"]); alert(json.name); 

You can also check this link: How to access JSON object in JavaScript

+13
source share

If you want to see all the data in a JSON object, use JSON.stringify For more details see here .

Hope this helps.

+4
source share

try console.log () it will log in to the console. alert does not display an object.

  $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ console.log(data) }, success: function(data){ console.log(data) } 
0
source share

just console.log (data) you will see your object.

you can access your value in something like this

 data.id //will give you id 

it is also up to you how you create this check for explanation

 // if it simply json then access it directly //Example => {"id":1,"value":"APPLE"} data.id; // will give you 1 // if it json array then you need to iterate over array and then get value. //Example => [{"id":1,"value":"APPLE"},{"id":2,"value":"MANGO"}] then data[0].id; // will give you 1 

so your code will be like this:

  $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ alert(data.status);// S1000 alert(data.description);// Success // for results you have to iterate because it is an array var len = data.results.length; for(var i=0;i<len;i++ ){ alert(data.results[i]); } }, success: function(data){ alert(data) } }) 
0
source share

data no longer in JSON format, it is a Javascript Object . You no longer need to use the jQuery.parseJSON function.

This is one of the common mistakes for beginners.

If you want to see this Javascript object, try alert(JSON.stringify(data));

0
source share

I think you are just printing an object. Try something like this

 $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ alert("status = "+data.status+"descripttion"+data.description); }, success: function(data){ alert("status = "+data.status+"descripttion"+data.description); } 
0
source share

Try data[0].status; . Your data is now in the object. In console.log(data) you can see that

0
source share

All Articles