Newbie
Newbie

Reputation: 249

How to access the returned object of JQuery "POST" method in javascript?

I have a JQuery "POST" method which returns value

Objects: [{"in_approved":0, "out_approved":0},{"in_approved":1, "out_approved":2}]

Ajax method:

$.ajax({
        data: {
                "start_date" : startDate,
                "end_date" : endDate
        },
        url: "/admin/analytics",
        type: 'POST',
        dataType: 'json',
        success: function(response)
        {

            // Accessing returned object

        },
        error : function(request, status, thrownError){
            alert("Error");
            return;
                }
    });

Now, to access the returned object I am using

$.each(response.data, function(index,row){
   var in_approved = row.in_approved; 
  alert(in_approved); // just to see if the value is being stored in the variable.
});

But when I do this I get an error:

Uncaught TypeError: Cannot read property 'length' of undefined

Can anyone explain to me what this error means?

Also how to access the values of the returned object?

Upvotes: 2

Views: 1067

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

The response is an array of Objects.. So you need to iterate over it as an array.

$.each(response, function(index,row){

But you are trying to iterate over response.data

your $.each will work on this object

data : [{"in_approved":0, "out_approved":0},{"in_approved":1, "out_approved":2}]

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 238115

response will be the array that you posted. It does not have a data property, so it will inevitably not be found when you look for it! Just loop through the array:

$.each(response, function(index,row){

Upvotes: 1

Related Questions