Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON object from AJAX call

I'm new to AJAX and javascript. In my project, I have to get a json object in my javascript file. I've 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 an alert [object Object]. What is the issue in here?

like image 910
Shashika Avatar asked Mar 06 '14 07:03

Shashika


People also ask

Can AJAX return JSON?

You couldn't directly return an array from AJAX, it must have converted in the valid format. In this case, you can either use XML or JSON format. In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.

How do I get AJAX response in JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.


1 Answers

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

you can access your value by something like this

data.id //will give you id

it also depend on you json how you are creating check this out 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)
    }
})
like image 113
rajesh kakawat Avatar answered Oct 06 '22 07:10

rajesh kakawat