1

I'm having a bit of difficulty here; I am using js to dynamically create select boxes, but I need Ajax to fill them with options. So far, my code is returning undefined, and I frankly don't know what to do here. My php returns the info fine, but the js isn't parsing it. Another set of eyes, or another brain full of knowledge would be appreciated here;

function getSkilllist(group) {
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
    xmlhttp.send();
}

function addInput(divName,group) {
var skillst = getSkilllist(group);
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="ski[]">' + skillst + '</select> .....

The rest of the function is fine, but the var skillst is returning undefined as stated, and I can't figure out why. I assume it has something to do with strings, but I can't figure out what needs to be done.

1
  • 1
    Remember that (normally) Ajax requests are asynchronous, so after the xmlhttp.send() your other code continues executing without waiting for a response and then the response from the Ajax request is processed later. So your getSkilllist function doesn't return anything at all, skillst will be undefined, but your other code continues and the div is created, etc. When the Ajax response comes in the anonymous function you defined for xmlhttp.onreadystatechange will execute, so that's where you need to create the div as per the answer below. Commented Jun 17, 2011 at 1:08

1 Answer 1

1

Your function does not return anything, which is why it isn't working. Try this:

function getSkilllist(group) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
       var newdiv = document.createElement('div');
       newdiv.innerHTML = '<select name="ski[]">' + xmlhttp.responseText + '</select> .....

       //place in DOM here
    }
}
xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
xmlhttp.send();
}

function addInput(divName,group) {
getSkilllist(group);
Sign up to request clarification or add additional context in comments.

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.