Solved

Using AJAX to Rerun Single Database Query on PHP Page

Posted on 2010-09-24
20
184 Views
Last Modified: 2014-01-21
We have a PHP page with lots of queries to a mySQL database.

The web page delivers a webcast stream which can be any one of 2 stream types ...

- test mode stream
- live stream

From the back end admin area, we can toggle from  test (status value=1) to live (status value=2).

When a user logs in to view the webcast, the page queries the database to check the status of the webcast at the time the user logs in and ...

- if in TEST mode it will return 'value=1' which then displays the test webcast stream
- if in LIVE mode it will return 'value=2' which then displays the live webcast stream

When it is time to go live, the administrator toggles to live mode, changing the webcast status from 'test' (value=1) to 'live' (value=2).

What we need is for the page to regularly query the database to identify when that change is made.

But we don't want the whole page to refresh because that will then restart the test webcast.

Basically we want to know when the result changes from '1' to '2' so that we can change the webcast to show the live feed.

Of course, once it shows the live stream (value=2) then we can stop running the queries.

The code we are using is ...

// get webcast details
$sql_webcast = "SELECT * FROM webcasts WHERE id='$wid' AND code='$code'";
$result_webcast = mysql_query($sql_webcast);
$row_webcast = mysql_fetch_array($result_webcast);

if($row_webcast[feed_type]=='1') {
$stream = TEST STREAM;
}
if($row_webcast[feed_type]=='2') {
$stream = LIVE STREAM;
} 

Open in new window

0
Comment
Question by:poldings
  • 9
  • 9
20 Comments
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
I'm assume you're asking how to do AJAX and PHP.

See link below as basic example.
http://www.w3schools.com/php/php_ajax_database.asp

Nothing really to it.  Just have an onclick/onchange event call javascript which calls your php page and returns the results.

0
 

Author Comment

by:poldings
Comment Utility
Thanks but I've spent hours doing the research already which is why I've posted here.

The above code is part of the page and is not a separate file.

I would assume it would be easy but I just can't see it.

Can you provide the code so I can drop it into the page?
0
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
Not able to test, but something like this.  Edit as necessary.

Two files...

1.  one HTML file
2.  Separate PHP file.

Not sure where the variables $wid' AND code='$code'" come from?
<html>

<head>



<script type="text/javascript">

function checkDB()

{



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("returnValue").innerHTML=xmlhttp.responseText;

    }

  }

xmlhttp.open("GET","poldingsCode.php",true);

xmlhttp.send();

}

</script>



</head>

<body>



<input type=button onclick="checkDB();" value="Check Database"><BR>



<input type="text" ID="returnValue"><BR>

<br />





</body>

</html>









--------------

PHP FILE NOW

--------------





<?





//poldingsCode.php



// get webcast details

$sql_webcast = "SELECT * FROM webcasts WHERE id='$wid' AND code='$code'";

$result_webcast = mysql_query($sql_webcast);

$row_webcast = mysql_fetch_array($result_webcast);



if($row_webcast[feed_type]=='1') {

$stream = TEST STREAM;

}

if($row_webcast[feed_type]=='2') {

$stream = LIVE STREAM;

} 



echo($stream);





?>

Open in new window

0
 

Author Comment

by:poldings
Comment Utility
Okay. That's nearly there however, we don't want it triggered by a button, we want it automated to check every 30 seconds.
0
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
I had to make a change to the HTML but see below.  Should kick off every 30 seconds.
<html>

<head>



<script type="text/javascript">

function checkDB()

{



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("returnValue").value=xmlhttp.responseText;

    }

  }

var url="updatestatus.php";

url=url+"?q="+str;

url=url+"&pid="+pid;

url=url+"&tid="+tid;

xmlhttp.open("GET","poldingsCode.php?ID=1"+str,true);

xmlhttp.send();

}

</script>



</head>

<body onLoad="window.setInterval('checkDB();',30000);">



<input type=button onclick="checkDB();" value="Check Database"><BR>



<input type="text" ID="returnValue"><BR>

<br />





</body>

</html>

Open in new window

0
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
Sorry - take out the button.
0
 
LVL 16

Accepted Solution

by:
carsRST earned 250 total points
Comment Utility
Man, I'm not on top of my game today.    :)

See adjusted code.


<html>

<head>



<script type="text/javascript">

function checkDB()

{



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("returnValue").value=xmlhttp.responseText;

    }

  }



xmlhttp.open("GET","poldingsCode.php"+str,true);

xmlhttp.send();

}

</script>



</head>

<body onLoad="window.setInterval('checkDB();',30000);">





<input type="text" ID="returnValue"><BR>

<br />





</body>

</html>

Open in new window

0
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
This is the code that will call the ajax javascript function multiple times:

<body onLoad="window.setInterval('checkDB();',30000);">
0
 

Author Comment

by:poldings
Comment Utility
Thanks. That looks pretty good. I will run some final tests tomorrow and update this post when I can confirm the results. Thanks again.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 16

Expert Comment

by:carsRST
Comment Utility
Good luck!
0
 

Assisted Solution

by:poldings
poldings earned 0 total points
Comment Utility
No joy with that I'm afraid. Even if I use the button to force the update it doesn't work.

I have however, had some success with this ...

<!--HEAD-->
<script language="javascript">
var XMLHttpRequestObject = false;

if(window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);

XMLHttpRequestObject.onreadystatechange = function()
{
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>


<!--BODY-->
<form>
<input type="button" value="get result" onclick="getData('script-checkstatus.php', 'targetDiv')" />
</form>




Using this code I can push the button and pull in the result from a dbase query in a separate file.

So, the next thing is ... how can I make this an automated update?

I have tried the following but it doesn't work ...


0
 

Author Comment

by:poldings
Comment Utility
Sorry, that last comment should be ...

I have tried the following but it doesn't work ...
<body onLoad="window.setInterval('getData();',3000);" >
0
 

Assisted Solution

by:poldings
poldings earned 0 total points
Comment Utility
I think we may be getting somewhere. The following seems to work ...

<body onLoad="window.setInterval('getData(\'script-checkstatus.php\', \'targetDiv\');',3000);" >

I am running more tests and will update this soon.
0
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
Based on your changes, that should work.
0
 

Author Comment

by:poldings
Comment Utility
I'm still struggling on the final bit ...

I can get the result to show using a DIV tag as follows ...

<div id="targetDiv"></div>

But I need to convert this to a PHP variable so that I can use it inside the JavaScript code that calls the video.

Do you know how I can convert that to PHP ?
0
 

Author Comment

by:poldings
Comment Utility
Just to clarify, I need the result to be something that I can insert into the middle of some Javascript code.

Maybe AJAX is not the best option?
0
 
LVL 16

Expert Comment

by:carsRST
Comment Utility
Sorry.  Been out of town.  Will try to get back to u today.
0
 

Author Comment

by:poldings
Comment Utility
Not a problem.

I think we have an alternative solution using an iFrame and a PHP "while loop". I need to continue tests but initial results are good.

If you do come up with an AJAX solution all well and good but I think we will run with the PHP solution for this project.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now