Return xmlhttp.responseText From AJAX Function

I’ve been racking my brain for a couple hours now and doing a lot of searching and I cannot seem to find an answer. I want to know if it is possible to return the xmlhttp.responseText value from an AJAX function to the function that originally called the AJAX function.


//	Set handler for server response.
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4)
		{
			if (xmlhttp.status == 200)
			{
				var my_response = xmlhttp.responseText;
				//	How can I return my_response?
			}
		}
	}

I want to return the my_response variable to the original caller. No matter what I try I have been unsuccessful. I even tried assigning it to the global window variable using window.my_response = xmlhttp.responseText but it ends up being undefined.

Every example I’ve seen of using AJAX pretty much does something inside of the if (xmlhttp.status == 200) part to update the web page. I really do not want to do that.

Can I return the value? Thanks for your help.

Are you getting a response?

alert(xmlhttp.responseText);

Yes. The AJAX works fine and everything. I was just wondering if it is possible to return a value from that section of code.

Right now, what I am doing is passing the name of a callback function to the AJAX code and assigning it to the global window object then calling it inside the “xmlhttp.status == 200” part where I would like to return it.

I thought I read something about not being able to return values from this AJAX script because it runs asynchronously. As I am still a beginner when it comes to Javascript, I really do not know.

Thank you for the reply. If it is possible to return a value such as I indicated in my first post, please let me know.

The onreadystatechange function executes long after the other parts of the script have finished, so there is nothing to return anything to.

Instead, you can pass the value to another function.

OK. Now I understand. Thank you for the info. :slight_smile: