Jump to content

Functions within functions OK solution?


EdgeWalker

Recommended Posts

I want to be able to pass a variable to a callback function for my AJAX base, but the only way I could think of to keep the variable in scope was to put the callback function INSIDE the main one.  Is that ok?  Better solutions?

 

function get_and_replace(url,div_id)
{
//Replaces the innerHTML of the div with the response from the the URL
createXMLHttpRequest();
xmlHttp.open("GET",url);
xmlHttp.onreadystatechange=callback;
xmlHttp.send(null);

function callback()
{
	if(xmlHttp.readyState==4)
	{
		if(xmlHttp.status==200)
		{
                                //HERE IS WHERE IS USE THE VARIABLE div_id
			div_element=document.getElementById(div_id);
			div_element.innerHTML=xmlHttp.responseText;
		}
	}
}
}

(I thought this was more of a general JS question than AJAX)

Link to comment
https://forums.phpfreaks.com/topic/103945-functions-within-functions-ok-solution/
Share on other sites

maybe you could use a global

 

//declare global outside function
var global_div_id
function get_and_replace(url,div_id)
{
global_div_id=div_id
        //Replaces the innerHTML of the div with the response from the the URL
createXMLHttpRequest();
xmlHttp.open("GET",url);
xmlHttp.onreadystatechange=callback;
xmlHttp.send(null);


}



function callback()
{
if(xmlHttp.readyState==4)
{
	if(xmlHttp.status==200)
	{
                         //HERE IS WHERE IS USE THE VARIABLE div_id
		div_element=document.getElementById(global_div_id);
		div_element.innerHTML=xmlHttp.responseText;
	}
}
}


Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.