0

My request ajax with json_encode:

[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"}, 
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]

var string = JSON.stringify(data);

var obj = $.parseJSON(string);

console.log(string);

var idHome = obj.idHome;

var photo = obj.Photo;


console.log(obj.idHome);

console.log(obj.Photo);

Problem with parsing json

console log :

[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]

undefined

undefined
3
  • Why not use $.getJSON instead of $.ajax? Commented Jun 18, 2013 at 18:52
  • I use $.ajax ! $.ajax({ url: "url", data: 'GET', dataType: 'json', Commented Jun 18, 2013 at 18:55
  • You've encoded an array... console.log(obj[0]); Commented Jun 18, 2013 at 19:03

2 Answers 2

2

It is an array so you need to loop through, there are so many ways to do it.

for (i = 0; i < obj.length; i++) {
    console.log(obj[i].idHome);
    console.log(obj[i].Photo);
}

or:

obj.forEach(function(val) {
    console.log(val.idHome);
    console.log(val.Photo);
});

or:

for (var i in obj) {
    console.log(obj[i].idHome);
    console.log(obj[i].Photo);
}

Jquery use :

 $.each(obj, function(_, val){
    console.log(val.idHome);
    console.log(val.Photo);
 });

and so on....

Sign up to request clarification or add additional context in comments.

2 Comments

Jquery use parse just {"idHome":"1","Photo":"home1.jpg","Publier":"1"}
@boube You want only the first one?
2

Your json is an array of three objects.

Try

console.log(obj[0].idHome);
console.log(obj[0].Photo);

More info: http://www.w3schools.com/json/json_syntax.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.