0

I received JSON post response as shown below . I want to iterate over JSON post response data and print the data in image divs (as shown).

Could any show me how this can be done using JavaScript ? Thanks

Javascript code the receives JSON post response :

cordovaHTTP.post(url,data,
  function(response) {
alert("Data: " + response.data + "\nStatus: " + response.status);

}

post request response received:

"[\r\n  {\r\n    \"itemID\": \"12345678\",\r\n    \"itemTitle\": \"mango\",\r\n    \"itemText\": \"\",\r\n    \"ThumbUrl\": \"http://awebsite.com/pics/1.jpg\",\r\n    \"Other\": null\r\n  },\r\n  {\r\n    \"itemID\": \"12345679\",\r\n    \"itemTitle\": \"orange\",\r\n    \"itemText\": \"\",\r\n    \"ThumbUrl\": \"http://awebsite.com/pics/2.jpg\",\r\n    \"Other\": null\r\n  }\r\n]"

Image divs that i want to print :

<div class ="image">
<a href="javascript:dofunction('./test.php?title=Mango&TargetUrl=http://somesite.com/12345678')">
<img src="http://awebsite.com/pics/1.jpg" alt=".." />
</a>
</div>

<div class ="image">
<a href="javascript:dofunction('./test.php?title=orange&TargetUrl=http://somesite.com/12345679')">
<img src="http://awebsite.com/pics/2.jpg" alt=".." />
</a>
</div>

Edit: I accept the answer below and i had to validate my actual api data using some replace functions by removing all \r\n and changing all itemText key values to "itemtext": "empty", using regular expression!

user1788736
  • 2,727
  • 20
  • 66
  • 110
  • Very easy to do with Knockout.js, which I highly recommend you take a look at. – connexo Oct 02 '16 at 16:53
  • You can loop over JSON and create HTML on your own. *Knockout/Angular/React* will ease your job but they add to load time and every framework/library has its own pros and cons. Do refer them before using them – Rajesh Oct 02 '16 at 16:57
  • Thanks for replies but i don't have experinece with Knockout/Angular/React.Is it possible to do it using for loop ? – user1788736 Oct 02 '16 at 17:00
  • @user1788736 this should help: http://stackoverflow.com/questions/2546372/jquery-loop-to-create-elements. Another reference link: http://stackoverflow.com/questions/2946656/advantages-of-createelement-over-innerhtml – Rajesh Oct 02 '16 at 17:03
  • Idea is there is 2 ways to create dynamic elements, 1. create element and attach it to container. 2. create html string and set it as innerHTML. Both approach have their benefits based on situation but you will have to take care of browser compatibility. – Rajesh Oct 02 '16 at 17:06
  • @Rajesh, I think jQuery mostly takes care of that. The OP just needs to worry about performance concerns, which is provided by the second method of yours. – Taha Paksu Oct 02 '16 at 17:10
  • @TahaPaksu it was just a caveat if OP plans to use vanilla JS. – Rajesh Oct 02 '16 at 17:13

3 Answers3

1

You can write something like this:

cordovaHTTP.post(url, data, function(response) {
    // first, convert the string to JSON data array structure
    var json = $.parseJSON(response.data);
    // then loop the single items
    for(i in json)
    {
       // create HTML code
       var div = "<div class=\"image\">" + 
       "<a href=\"javascript:dofunction('./test.php?title=" + json[i].itemTitle + "&TargetUrl=http://somesite.com/" + json[i].itemID + "')\">" +
       "<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />" +
       "</a>" +
       "</div>";
       // append it inside <body> tag.
       $("body").append(div);
    }
});
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
  • Just a pointer, its a bad practice to manipulate DOM in loop. – Rajesh Oct 02 '16 at 17:14
  • Thanks for replies. @Taha Paksu i tried your solution but i got no dive printed! My JSON response is not same as your edit version of my initial JSON response sample !How to remove those backward slashes,double quotes at start and end of data ?Should i place a dive called body ?Furthermore, as you see i want to print the divs inside two other dives !Hope you help me fix this problem. – user1788736 Oct 02 '16 at 17:48
  • 1. I rolled my edits back to the original state. 2. `$.parseJSON` handles that. – Taha Paksu Oct 02 '16 at 17:53
  • I tried it with real api data and i get undefined for all json values! I tested json on http://jsonlint.com/ it said it is valid but for some reason i get undefined for div variables.Is there a way to find what might be the problem? – user1788736 Oct 03 '16 at 11:46
  • did you use `$.parseJSON()`? try with `var json = $.parseJSON(data); console.log(json);` and see what's written in the browser console. – Taha Paksu Oct 03 '16 at 11:56
  • Yes i used json = $.parseJSON(data); and i used console.log(json); and clicked f12 and on console window i see the json printed nicely but itemText(another key in json that i don't want it) are multi line and they have some � mark on some part of it! Is there a way to remove itemText key from json before parsing it ? – user1788736 Oct 03 '16 at 12:30
  • 1
    You can search it in StackOverflow about how to modify JSON structures. – Taha Paksu Oct 03 '16 at 12:36
0

IMO, use concatenate += of string rather than every time append HTML to the body inside a loop.

In addition of @Taha Paksu answer.

cordovaHTTP.post(url, data, function(response) {
    // first, convert the string to JSON data array structure
    var json = $.parseJSON(response.data);
    // then loop the single items
    var div = "";
    for(i in json)
    {
       // create HTML code
       div += "<div class=\"image\">" + 
       "<a href=\"javascript:dofunction('./test.php?title=" + json[i].itemTitle + "&TargetUrl=http://somesite.com/" + json[i].itemID + "')\">" +
       "<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />" +
       "</a>" +
       "</div>";
    }
    // append it inside <body> tag once the loop completes
    $("body").append(div);

});
Mohit Tanwani
  • 6,608
  • 2
  • 14
  • 32
0

As commented before, there are 2 ways to create dynamic elements

  • Create html string and set it as innerHTML
  • Create dynamic elements using document.createElement and append it to container.

Following is a sample representing creation of HTML string:

Note: There are different ways to loop. You should choose them based on your use case. I have use array.reduce for sample but you can achieve same result using for or any other method.

var data = [{
  "itemID": "12345678",
  "itemTitle": "mango",
  "itemText": "",
  "ThumbUrl": "http://awebsite.com/pics/1.jpg",
  "Other": null
}, {
  "itemID": "12345679",
  "itemTitle": "orange",
  "itemText": "",
  "ThumbUrl": "http://awebsite.com/pics/2.jpg",
  "Other": null
}]

function createHTML(obj) {
  var _href = "./test.php?title=" +obj.itemTitle+ "&TargetUrl=http://somesite.com/" + obj.itemID
  var _html = '<div class ="image">' +
    '<a href="javascript:dofunction('+_href+')">' +
    '<img src="' +obj.ThumbUrl+ '" alt=".." />' +
    '</a>' +
    '</div>'
  return _html;
}

var _html = data.reduce(function(p,c){
  return p + createHTML(c)
},'');

console.log(_html)
Rajesh
  • 24,354
  • 5
  • 48
  • 79