I have the following javascript function, which uses .append from JQuery. However it only works if I add alert() at the beginning of the function. I have found out the reason for this behavior is due to the asynchronous way AJAX works.
How can I make sure that this function displays the html as wanted?
this.printJSON = function(id) {
//alert(id);
$(id).append('<button id="#store">store</button>');
for(key in params) {
$(id).append('<p '...'</p>');
}
};
my whole class, which is called this way:
params.parseJSON();
params.printJSON("#showdata");
function Parameters(parametersFile) {
//private stuff
var paramFile = parametersFile;
var params = {};
//public stuff
this.parseJSON = function() {
$.getJSON('inputFileParametersJSON.txt', function(json) {
for(var param in json) {
for(var key in json[param]) {
if(json[param].hasOwnProperty(key)) {
params[key] = {
filterIdentifier : json[param][key].filterIdentifier,
paramIdentifier : json[param][key].paramIdentifier,
param : json[param][key].param
};
}
}
}
});
};
this.printJSON = function(id) {
alert("");
$(id).append('<button id="#store">store</button>');
for(key in params) {
$(id).append('<p id="' + key + '"> filterIdentifier: ' + params[key].filterIdentifier + '<br /> paramIdentifier: ' + params[key].paramIdentifier + '<br /> param= <input type="text" id="' + key + '"name="param" value="' + params[key].param + '"/></p>');
//alert(params[key].filterIdentifier);
}
};
}
As jcm has said, you should be calling
printJSON()from the response handler to enable it to work once the results of the request have been used to populateparams.Here be monsters
If you really need to wait for the result of an ajax post and can’t use the result in a response handler (which is almost never), you can set
asyncto false (see http://api.jquery.com/jQuery.ajax/), but since JS is executed in a single thread, this will halt execution of the JS until the request is completed.Since you are using
$.getJSON()you would need to use theajaxSetuphttp://api.jquery.com/jQuery.ajaxSetup/ to change the behaviour of the ajax call.