0

Continuing to develop my first web-service, faced a new problem... I have a javascript function, which is provide a JSON object as array.

function RequestData(i){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/getitemID='+i, true);
    xhr.send();
    xhr.onreadystatechange = function() { // (3)
        if (xhr.readyState != 4) return;
        if (xhr.status != 200) {
            alert(xhr.status + ': ' + xhr.statusText);
        } else {
            alert(xhr.responseText);
            var jsonData = JSON.parse(xhr.responseText);
            for (var j=0; j< jsonData.length; j++  ){
                alert(jsonData[j].name);
            }
        }

    }
    xhr.close();
}

there is an array with entities in jsonData like "name", "description", etc

The question is, how can i display a resulting JSON array on the html body of the page? like in foror foreach cycle

need just a simple example. imagine this how the JS file make the content of page

var contentString = '<div id="content">'+
    '<div id="bodyContent">'+
    '<button onclick="RequestData('+i+')">Load Data!</button>'+
    '</div>'+
    '</div>';

i want to insert a result from RequestData() function into the content of variable "var contentString"

user1935987
  • 3,136
  • 9
  • 56
  • 108

2 Answers2

0
for (var j=0; j< jsonData.length; j++  ){
    GetHTML(j);
}

function GetHTML(j) {
    var divwrapper =  document.CreateElement('div');
    var innerdivwrapper =  document.CreateElement('div');
    var textnode = document.createTextNode("my Name :" + j.Name + 'desc' + j.Description); 
    innerdivwrapper.appendChild(textnode);
    divwrapper.appendChild(innerdivwrapper);
    document.getElementsByTagName('body').appendChild(divwrapper);
}
Andy
  • 61,948
  • 13
  • 68
  • 95
Dreamweaver
  • 1,328
  • 11
  • 21
  • The OP isn't using jQuery. – Andy May 22 '15 at 10:32
  • Your code won't run (missing `)`, capital F in `Function`, using `j` as iterating variable but indexing the array with `i`) and could have nicer formatting. – Peter Herdenborg May 22 '15 at 10:33
  • Formatting still terrible, and `document.getElementByTagName('body')` won't work, should be `document.getElementsByTagName('body')[0]` – Peter Herdenborg May 22 '15 at 10:43
  • sorry abt that, will correct, but still it gives an idea to solve the problem. – Dreamweaver May 22 '15 at 10:45
  • Yeah, it's just nice with working and decently looking code :) -1 removed now, despite the formatting. – Peter Herdenborg May 22 '15 at 10:46
  • Thanks, next time onwards will keep this in mind.. .. :) – Dreamweaver May 22 '15 at 10:47
  • You should look into [`insertAdjacentHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) like in my example. – Andy May 22 '15 at 10:50
  • Also, you should cache the body element at the start so you're not picking up from the DOM every iteration of the loop. And you should also be using a document fragment. Your example is tremendously inefficient. – Andy May 22 '15 at 10:54
  • Its was to give an idea, but next time onwards will keep in mind to give exact solution. And never used documentfragment, so did not know about it. Thnaks for adding the extra knowledge (read here http://stackoverflow.com/questions/3397161/should-i-use-document-createdocumentfragment-or-document-createelement):) – Dreamweaver May 22 '15 at 12:04
0

You should probably use a callback here.

function RequestData(i, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/getitemID='+i, true);
    xhr.send();
    xhr.onreadystatechange = function() { // (3)
        if (xhr.readyState != 4) return;
        if (xhr.status != 200) {
            alert(xhr.status + ': ' + xhr.statusText);
        } else {

            // pass the parsed data as the parameter of the callback
            callback(JSON.parse(xhr.responseText));
        }

    }
    xhr.close();
}

// i is the id we're passing into the function
// and that is used in the xhr.open command
// this is an example
var i = 23;

// i gets passed in as the first parameter,
// the json gets passed as the second parameter to the callback
RequestData(i, function (json) {

  // we create a little template using an array
  var tmpl = [
    '<div id="content"><div id="bodyContent">',
    '<button onclick="RequestData(#name)">Load Data!</button></div></div>'
  ].join('');

  var body = document.querySelector('body');

  for (var i = 0, l = json.length; i < l; i++) {

     // replace the name in the template with the json name for that index
     var html = tmpl.replace('#name', json[i].name);

     // use insertAdjacentHTML to add that HTML string to the body element
     body.insertAdjacentHTML('afterbegin', html);
  }

});

You can read more on the widely supported insertAdjacentHTML on the MDN page (it's the first I've heard of it!). And here's an example of it working.

Andy
  • 61,948
  • 13
  • 68
  • 95
  • but, why is it better to use a callback? and, from where did i pass a callback to "function RequestData(id, callback)" here? – user1935987 May 22 '15 at 11:10
  • It makes your code simpler. And the function is the one that's passed as the second argument in the line: `RequestData(id, function (json) {` – Andy May 22 '15 at 11:15
  • why can't i transfer id in callback function? `RequestData(id, function (json) {` "unresolved type of variable id" – user1935987 May 22 '15 at 16:37
  • else if i do this: `callback(i, JSON.parse(xhr.responseText));` `RequestData(function (i, json) {}` getting a "Uncaught TypeError: callback is not a function" error. i'm really new to web-programming, can't get, what is wring here? how to pass 'i' ? – user1935987 May 22 '15 at 17:30
  • `i` is the first parameter that represents the query id you're using. I used `id` in my example because it's more explanatory. There's no need to pass it back in the callback. So just use my code for that. Then you do `RequestData(i, function (json` because you're passing in that id into `RequestData` as the first parameter. I've updated my code to make this more explanatory. – Andy May 23 '15 at 02:19
  • yes, i understand that. but the thing is that in yout example, you define 'i' as a global variable.. yesm in this case it's working ok. But i have to pass this id to `function RequestData(i, callback) {` and it`s callback trough other func. as example, i have `function MyFunc() { var id =27; RequestData(i); }` and if i do as in your example, here `RequestData(i,function (json) {}` i`m receiving a error 'unresolved type or variable 'i'' – user1935987 May 23 '15 at 02:46
  • So, if i try to do as in your example, calling callback like this: `function RequestData(i, callback) {` - i get 'unresolved type or variable 'i'' error, and callbacl doesn't work. else if i do not pass 'i' in callback - i do not get this error, but looks like callback doesn't work too, because this code for callback don't work `RequestData(function (json) { alert('here!');}` - i don't receive a message 'here', but no errors. in both situations callback call is like this: `callback(JSON.parse(xhr.responseText));` – user1935987 May 23 '15 at 10:21