javascript async call and adding results to a div

I have something similar to the below code and when I tried to add the label within the callback function it does not work.
How can I solve this problem?



//This is an async ajax soap call which returns an array of labels to be added.
 var asyncFunction = function(param, handler){

  }

    var createDiv = function(){
        var containerDiv = document.createElement("div");

        asyncFunction("some", function(response){
            var labelOne = document.createElement("label");
            labelOne.innerHTML = response[0];
            containerDiv.appendChild(labelOne);                                            <------- Adding it here??
        });
        return containerDiv;
    }

    document.getElementById("MainID").appendChild(createDiv());

Open in new window

ambuliAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Russ SuterSenior Software DeveloperCommented:
Some browsers don't play nice if you try to add an element to the DOM without the id attribute set. Try setting the id property of labelOne before appending it to the containerDiv.
Alexandre SimõesManager / Technology SpecialistCommented:
Hi mate,
your code should work, what kind of issue do you get?
Does it throw an error?

If I had to guess I would say that your problem is in the ajax call itself. Probably is throwing an error or not returning the expected data.
Use the browser dev tools (F12) to see if you have any errors.
Also try to print the ajax call result to the console or see it in the network tab.

Here's a small demo that simulates the problem with a setTimeout: http://jsfiddle.net/AlexCode/s31pu4uq/
var createDiv = function () {
    var containerDiv = document.createElement("div");

    setTimeout(function () {
        var labelOne = document.createElement("label");
        labelOne.innerHTML = 'My demo text';
        containerDiv.appendChild(labelOne); //< -------Adding it here ? ?
    }, 500);
    return containerDiv;
}

document.getElementById("MainID").appendChild(createDiv());

Open in new window

Julian HansenCommented:
Your code works - consider this sample
jQuery / Javascript
<script>
function asyncFunction(param, handler) {
  $.ajax({
    url: 't1160.php',
    data: {param: param},
    dataType: 'json',
    type: 'POST'
  }).done(function(response) {
    handler(response);
  });
}

var createDiv = function(){
  var containerDiv = document.createElement("div");

  asyncFunction("some", function(response){
    var labelOne = document.createElement("label");
    labelOne.innerHTML = response[0];
    containerDiv.appendChild(labelOne);
  });
  
  return containerDiv;
}
document.getElementById("MainID").appendChild(createDiv());
</script>

Open in new window

Sample PHP script that returns the data
<?php
$param = isset($_POST['param']) ? $_POST['param'] : 'notset';
$response = array( 
   "label: " . $param
);

// simulate delay
sleep(5);

die(json_encode($response));

Open in new window

Working sample here

Check your console for errors and view what is returned by Asynch function

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.