PDA

View Full Version : JS not working in Ajax loaded page



dracula51
10-29-2009, 05:01 AM
hey.
i hav a file, suppose, name.php. it contains various things with a <div id="ajax-content">

another file is name_ajax.php

i use these codes to load contents from name_ajax.php in name.php's DIV


var xmlHttp


function pagination(page)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="name_ajax.php?starting="+page;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("ajax-content").innerHTML=xmlHttp.responseText;
}
}



function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}

return xmlHttp;
}

actually i use it for an ajax pagination system.
btw, in name_ajax.php there are some javascript code. & they r not working when loaded in name.php's DIV area
thats the problem JS is not working when loaded via ajax
plz help me

ps: sorry for bad english & im not an expert JS coder

bluewalrus
10-29-2009, 05:50 AM
I'm not a js coder but that first line looks wrong to me. I think you need to close it with a ";" or set it to a value then close it. The line "var xmlHttp".

jscheuer1
10-29-2009, 06:58 AM
That's actually OK, just sloppy. The thing is that the type of AJAX import you are doing will not (in like 99.99% of cases) execute javascript code from the imported page. For that you need some other approach. I generally put the script I want to use hard coded on the page I am importing to and rely upon javascript events (either hard coded or listened for) of the imported content's elements to activate the main script which is on the main page. Scripts that must initialize onload will not work with this approach without modification and/or a helper function to initialize the imported content once it is present.

As you can see it can get complicated.

The jQuery script library can take care of some of this stuff for you, but one still needs to understand the general principals (as outlined above) and have some grasp of jQuery.

That said, I'm sure you will find these pages from the online jQuery documentation interesting:

http://docs.jquery.com/Ajax

especially:

http://docs.jquery.com/Ajax/jQuery.getScript