PDA

View Full Version : Ajax Not Loading jQuery Scripts On Main Page



M2com
07-23-2014, 04:19 PM
Hi!

On my page, a user will click on an image which sends data to an ajax script which in turn sends a variable to a PHP script on another page. Ajax gets the response and replaces a DIV's content with that PHP's page's content. It will work except for the fact that jQuery won't load for that PHP page.

JS Function:

function wearitem(name) {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;

document.getElementById("loadoutdisplay").innerHTML=response;
}
}
xmlhttp.open("POST","loadout.php?wear="+ name,true);
xmlhttp.send();
}

The PHP page is just pure PHP and HTML, there isn't any Javascript. All the JS stuff is on the page of the JS function above.

Thanks in advance and let me know if you need any more info.

-M2com

jscheuer1
07-23-2014, 07:36 PM
Many scripts initialize onload, or at document ready. Either way, that's over by the time this code:


if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;

document.getElementById("loadoutdisplay").innerHTML=response;
}

executes. If you need to initialize the new content, this code is also where you would do that:


if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;

document.getElementById("loadoutdisplay").innerHTML=response;
// initialize the new content here
}

but it can be complicated. For instance different content might be returned at different times and therefore perhaps need different treatment. And/or the script who's initialization routine you wish to run at that point might not be able to do so for one reason or another.

Using jQuery ajax() and/or live() (for older versions) or on() (for jQuery 1.8+) can often simplify some of this.

If you want more help, please provide a link to the page on your site that shows the problem(s).