...

View Full Version : Run a PHP script without slowing down page-load



roper22
02-26-2012, 11:39 PM
Hey guys. I host a private website that I use to broadcast my DJ mixes live to my friends. I'm currently using a PHP script on the home-page to say whether I'm broadcasting currently, or if I'm offline. The script works great, but it really slows down the page loading time.

Is there a way to have the page load, and then just have the "Status:" say "Checking..." until the PHP script can determine if I'm streaming or offline?

This is my PHP code:

<?php
if (url_validate($link)) {
echo "LIVE";
} else {
echo "OFFLINE";
}
?>

Thank you!

Old Pedant
02-27-2012, 12:14 AM
Sure...use AJAX.

http://www.w3schools.com/ajax/default.asp

Let your page come up first, then have it call PHP via AJAX.

roper22
02-27-2012, 12:26 AM
Thank you for the advice! I feel like I'm reading Chinese right now but maybe I can figure this out.

roper22
02-27-2012, 12:44 AM
Okay so this is where I'm at now:

I have this script in my <head> tags, and I want it to go to livefunction.php and see what it's echoing.

<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","livefunction.php",true);
xmlhttp.send();
}
</script>

Notice it is trying to change the text of myDiv. I have myDiv in my body.
<div id="myDiv" align="center">Checking...</div>

As to let the page load, I've called this function at the very end of my <body> tags
<script>
window.onload=loadXMLDoc;
</script>

Finally, this is livefunction.php

if (url_validate("http://74.88.8.67:8000/VirtualDJ.mp3")) {
echo "<a href=live.php?u=mltn>LIVE!</a>";
} else {
echo "OFFLINE";
}

My page just sits at "Checking..." and does not seem to be retrieving any data.

EDIT: SOLVED

Here was my solution for anyone wondering:

The code in this post was correct, all except for the Javascript function I was using to call the function. Rather than window.onLoad, I just did this <body onLoad="function();"> and that worked perfectly.

Old Pedant
02-27-2012, 01:34 AM
Not bad at all if this is your first encounter with AJAX! Impressive, even. Congrats.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum