0

I stucked a little bit in here>

My php script returns this JSON (in variable response) (encoded array with json_encode) :

{"1":{"id":"pvv001","tooltip":"tip1","link":"http:\/\/domain\/file1.html"},"2":{"id":"pvv002","tooltip":"tip2","link":"http:\/\/domain\/file2.html"}} 

I hope this is valid JSON object ...

Then here is JavaScript function which should get this string and process it - load to ELEMENT "id" a content of "link".

function jLinks(idchapter) { var url = 'ajax_loadlinks.php'; var data = { idchapter : idchapter }; $.post(url,data, function(response) { //$('#coursecontent').html(response); var obj = JSON.parse(response); for (var i=0; i<obj.length; i+1) { $('#'+obj[i].id).html('<a href="'+obj[i].link+'">link</a>'); } }); } 

It is not throwing any error in browser or console, but elements are not updated at all.

I quess my parsing and accessing data is wrong somehow, but I have no idea how to debug.

5
  • 1
    Your JSON is not describing an array, it is instead describing a regular object,. So obj isn't going to have a length property, therefore your loop never runs. Commented Oct 5, 2017 at 11:43
  • try with for (var i=0; i<obj.length; i++) in place of for (var i=0; i<obj.length; i+1) Commented Oct 5, 2017 at 11:44
  • json need to be enclosed in between[] Commented Oct 5, 2017 at 11:44
  • You have to fix this via PHP, make sure it is an array that is being parsed into JSON. Commented Oct 5, 2017 at 11:45
  • so, does this mean problem is with passed JSON string itself ? this is how do it (rows are fetched from DB)> <code> $x=0; foreach ($rows as $row) { $x++; $link = $row['link']; $linkid = $row['linkid']; $linktooltip = $row['linktooltip']; $result[$x]['id']=$linkid; $result[$x]['tooltip']=$linktooltip; $result[$x]['link']=$link; } } $return = json_encode($result); echo $return; </code> sorry, i dont know how to format code he in comment ... Commented Oct 5, 2017 at 11:54

2 Answers 2

4

As your string is an object not array, so you need $.each method to loop over each key of object.

var obj ={ "1": { "id": "pvv001", "tooltip": "tip1", "link": "http:\/\/domain\/file1.html" }, "2": { "id": "pvv002", "tooltip": "tip2", "link": "http:\/\/domain\/file2.html" } }; $.each(obj,function(i,v){ $('#'+v.id).html('<a href="'+v.link+'">link</a>'); }); 

Fiddle

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

1 Comment

thank you very much, this solve my problem! elemets are updated now with this $each loop.
0

please try this

 for (var prop in obj) { if (obj.hasOwnProperty(prop)) { console.log(obj[prop].id); $('#'+obj[prop].id).html('<a href="'+obj[prop].link+'">link</a>'); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.