views:

61

answers:

2

Ok I've looked everywhere for this. I'm cutting out a couple of the variable declarations, as I can ensure that my XMLHttpRequest is working.

function submit_edit_form()
{
    // id and title are already declared
    var x = ajax_edit_form_save(id, 'title', title);
    alert(x);
}
function ajax_edit_form_save(id, property, new_value)
{

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        // screw IE5 & IE6
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
       if (xmlhttp.readyState == 4 && xmlhttp.responseText != '')
       {    
            return xmlhttp.responseText;
       }
    }

    // myURL is already defined. I'm not troubleshooting this part, I know it's working
    xmlhttp.open("GET", myURL, true);
    xmlhttp.send();
}

So when I call submit_edit_form(), which calls ajax_edit_form_save(), I get an alert 'undefined'. I know that the problem is that ajax_edit_form_save() is returning undefined on readyState 1. I'm scratching my head because I only have the return when readyState == 4. How can I hold off on the return value so that x gets the actual responseText?

+1  A: 

Your function is returning even before the ajax call completes, since it is async. The return statement in your "onreadystatechange" will not have any effect because the value is returned to the caller of the method "onreadystatechange" which is the XMLHttpRequest obejct and not your code.

You should pass a callback function to your ajax_edit_form_save which is called when readystate is 4

See below:

function ajax_edit_form_save(id, property, new_value, funCallback) // ==> callback function
{

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        // screw IE5 & IE6
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
       if (xmlhttp.readyState == 4 && xmlhttp.responseText != '')
       {    
            callback( xmlhttp.responseText ); // =============> callback function called
       }
    }

    // myURL is already defined. I'm not troubleshooting this part, I know it's working
    xmlhttp.open("GET", myURL, true);
    xmlhttp.send();
}

The call back function could be:

function handleReponse(resp) {
  // do something with resp
}

ajax_edit_form_save("myID", "myProperty",  "new value", handleResponse);
naikus
dude I think I love you. I completely didn't think about this. I'm about to check it out and I'll give you the check.
Adam Tootle
ok I can totally take that and work with it. Thank you!
Adam Tootle
@Adam Tootle You are welcome!
naikus
A: 

Where did you get that (x) from which file? I think, you forgot to mention URL value.

ppshein
that wasn't the issue. I know the request was functioning correctly. I just need to handle the return value.
Adam Tootle