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
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;
	}
}
}


Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.