kittymeows
kittymeows

Reputation: 183

JSON - get the values

JSON

  {
          "items": 
          [
            {
              "name": "Project title",
              "id": 16,
              "image": "\u002fimages\u002fdefault.png",
            },
            {
              "name": "Project title",
              "id": 25,
              "image": "\xxx",

            },
     ]
    }

JQquery

var getDataUrl = '/data';

$.ajax({
    url: getDataUrl,
    type: 'GET',
    dataType: 'json',

    success: function( response ){
      console.log(response + 'get?');
      $.each(response, function() {
        console.log(response.name + 'get?');
    });
    },
    error: function(error) {
      console.log( error)
    }
  });

Trying to get the responses' value to print but not sure why it is not displaying name. I need to get name, id and image but for now test and see if name is displayed...

Help appreciated, thanks.

Upvotes: 0

Views: 80

Answers (5)

Ajitabh
Ajitabh

Reputation: 1

First check the JSON Payload,i guess one comma is extra before']'.

Function should be like this...

$.each(response.items, function(i, j) {
    console.log(response.items[i].name);
});​ 

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115282

Change response to response.items

success: function(response){
    $.each(response.items, function(i,v) {
        console.log(v.name + 'get?');
    });
}

Documentation : http://api.jquery.com/jquery.each/

Upvotes: 2

Salman Arshad
Salman Arshad

Reputation: 272446

The syntax of jQuery.each is:

jQuery.each( collection, callback(indexInArray, valueOfElement) )

In your example you need to change your code like this:

$.each(response.items, function(i, v) {
    console.log(v.name + 'get?');
});

Upvotes: 1

tankerjoe
tankerjoe

Reputation: 146

For your success function try:

$.each(response.items, function(i,v) {
    console.log(v.name + 'get?');
});

Also, double check that you have valid JSON. I think it is choking on the backslashes in your strings. You can validate at a site like http://jsonlint.com/

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 32831

I think you meant to do this:

$.each(response.items, function() {
    console.log(this.name + 'get?');
});

Upvotes: 4

Related Questions