migroo Posted November 9, 2011 Share Posted November 9, 2011 I'm trying to call an AJAX request from a java script function and I want to put the result into a variable so I can use it later in the function:The entire function is quite long. Here is the relevant part: if(type == "obitNextPage"){ message[0] = "infoRequest"; message[1] = "obitNavContent"; message[2] = "/supportingPHP/obitView.php"; message[3] = 4; message[4] = "obitNavTotalEntries"; pageNumTotal = sendRequest(message); pageNumCurrent = document.getElementById('pageNum').value; document.getElementById('obitNavContent').innerHTML = pageNumTotal;} Here is the sendRequest() function: function sendRequest(message){ var i = 4;var str = ""; //Generate the Str Varstr = "?message=" + message[3];while(i <= message[3]){str += "&var" + i + "=" + message[i];i++;}//Send the requestif(message[0]){if (window.XMLHttpRequest){request = new XMLHttpRequest();}else{request = ActiveXObject("Microsoft.XMLHTTP");} request.onreadystatechange = function(){if(request.readyState==4 && request.status==200){if(message[0] == "updateObitNavSearch"){document.getElementById(message[1]).innerHTML = request.responseText;}if(message[0] == "infoRequest"){return request.responseText;}}}request.open("GET", message[2] + str, true);request.send();}} I think I'm missing something simple but I've looked all over and I can't find anything on out how to do this. I could find a work around this time but I would like to know how to do this for future reference. Thanks. Link to comment Share on other sites More sharing options...
JamesB Posted November 9, 2011 Share Posted November 9, 2011 the reason it's not working atm is because this: pageNumTotal = sendRequest(message); is expecting sendRequest() to return a value, but the sendRequest() function doesn't return a value. one option would be to use false as the 3rd argument to open() and have the return request.responseText after the send() line, but this will pause javascript until the request completes or fails. a better option would be to use true as the 3rd argument to open() (like you are now), then inside the onreadystatechange() function, instead of returning a value, call a function sending the response text to it, which can then set the innerHTML. Link to comment Share on other sites More sharing options...
migroo Posted November 11, 2011 Author Share Posted November 11, 2011 Thank you! It worked great. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.