0

I make an ajax call that returns json data and tells me what html template to load and also the data needed to populate the template. If I load the template outside of the ajax call the data populates fine, however if i try and load the html within the ajax call, i see the html elements have loaded, but i am unable to populate them.

$.ajax({
type: "POST",
url: "http://some-url/items-json/item_data.json",
dataType: "json",
async: true,
success: function( data ) {

     // template_name will be an html file like template_10.html
     // #player-template is the div id i want to load it into   
     $('#player-template').load(data.template_name);


    // these elements get created from the dynamic template that gets loaded above
    $('#ques_intro').html(data.ques_intro);
    $('#question').html(data.question);
  } 
});

2 Answers 2

1

use the complete call back argument of load, so that the elements added during load #ques_intro etc is accessible once the load is complete. Other wise it will run load and other statements as load being async.

 $('#player-template').load(data.template_name, function(){ // <-- Call back executes after the load is complete.
    $('#ques_intro').html(data.ques_intro); //Now you can access the elements as they will be available in DOM
    $('#question').html(data.question);

   });

.load( url , complete(responseText, textStatus, XMLHttpRequest) )

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

Comments

1

A simple approach would be to specify a callback handler so that you wait until your template has been loaded to insert the content.

As per the jQuery.load spec, you simply need to pass in a callback handler after the load argument.

For example..

$('#player-template').load(data.template_name,function(){
    $('#ques_intro').html(data.ques_intro);
    $('#question').html(data.question);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.