0

I am populating a table with a Jquery Template. In this template, I need to use a json file through a ajax call to populate.

$(document).ready(function() {
    var clientData;

    $.get("/webpro/webcad/lngetusuario", function(data, status){
        clientData = data;
        alert(clientData);
    });
    $("#clientTemplate").tmpl(clientData).appendTo("tbody");

});

<script id="clientTemplate" type="text/html">
    <tr><td> ${usuario} </td><td> ${nome} </td><td> ${setor} </td></tr>
     //{{tmpl($data) "#phoneTemplate"}}
</script>

The url '/webpro/webcad/lngetusuario' generate the json file.

This is the code. I don't understand this, because inside $.get statement the variable clientData are with the correct value json, but outside $.get statement(on document.ready) the variable clientData are empty.
Can anyone help me with this?

2 Answers2

0

It's a callback "feature".

The code isn't run in the order you think:

$(document).ready(function() {
    var clientData;

    $.get("/webpro/webcad/lngetusuario", function(data, status){
        clientData = data; // This will be run when a response has been received from the server
        alert(clientData);
    });
   // This will run without waiting any reply from the server
    $("#clientTemplate").tmpl(clientData).appendTo("tbody");

});

Here is want you need:

$(document).ready(function() {
    var clientData;

    $.get("/webpro/webcad/lngetusuario", function(data, status){
        clientData = data;
        alert(clientData);
        $("#clientTemplate").tmpl(clientData).appendTo("tbody");
    });

});
oliverpool
  • 1,624
  • 13
  • 30
0

$.get() is asynchronous. So $().tmpl() executes before $.get() is done, resulting in clientData being empty. To fix this put $().tmpl() inside the $.get() callback. This will make sure that your template will only be created when the get request is complete. Like so

$.get("/webpro/webcad/lngetusuario", function(data, status){
    clientData = data;
    alert(clientData);
    $("#clientTemplate").tmpl(clientData).appendTo("tbody");
});
Yvo Cilon
  • 372
  • 3
  • 14