AJAX Div Retrieval every 60 seconds - php

What I would like to do is retrieve the contents of a PHP file and insert it into a div every 60 seconds, basically refreshing the dynamic div. I've come up with the following code so far, however it doesn't seem to be working. The code is just like this, nothing extra, apart from the MYSQL login.
PHP to grab:
<?php
$time = date("m/d/Y h:i:s a", time());
mysql_query("UPDATE djs SET requesttime='{$time}' WHERE username='{$djs['username']}'")
or die(mysql_error());
$request_db = mysql_query("SELECT * FROM requests
WHERE haveplayed='0'") or die(mysql_error());
echo "<table style=\"border:1px solid;width:99%;margin-left:auto;margin-right:auto;\" border=\"1\">";
echo "<tr><th>Title</th><th>Artist</th><th>Dedicated To...</th></tr>";
while($request = mysql_fetch_array( $request_db )) {
echo "<tr><td style=\"width:33%;padding:1px;\">";
echo $request['SongName'];
echo "</td><td style=\"width:33%;\">";
echo $request['Artist'];
echo "</td><td style=\"width:33%;\">";
echo $request['DedicatedTo'];
echo "</td></tr>";
}
echo "</table>";
?>
The original PHP code is just the same, enclosed in a div with an id attribute of 'ajax_table'.
The JavaScript is:
// JavaScript Document
var xmlHttp_moniter
function moniter()
{
xmlHttp_moniter = GetXmlHttpObject_parcel()
if(xmlHttp_moniter == null)
{
alert("browser does not support HTTP Request")
return
}
var url="ajax_table.php?random=" + Math.random()
xmlHttp_moniter.onreadystatechange = stateChanged
xmlHttp_moniter.open("GET",url,true)
xmlHttp_moniter.send(null)
}
function stateChanged()
{
if(xmlHttp_moniter.readyState==4 || xmlHttp_moniter.readyState == "complete")
{
document.getElementById("ajax_table").innerHTML = xmlHttp_moniter.responseText
setTimeout('ajax_table()',60000);
}
}
function GetXmlHttpObject_parcel()
{
var xmlHttp_moniter=null;
try
{
xmlHttp_moniter=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp_moniter=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp_moniter=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp_moniter;
}
and that is on the page that is requesting the other php page.

How about using a framework like jQuery to simplify your javascript:
$(function() {
setInterval(function() {
$.get('ajax_table.php', function(data) {
$('#ajax_table').html(data);
});
}, 60 * 1000);
});

At first, there's no js function ajax_table() called in
setTimeout('ajax_table()',60000);
in your code.
At second point, are you sure you are calling moniter() function somewhere for the first time?

Try this, You can retrieve the contents of a PHP file and insert it into a div for every 60 seconds http://www.webtrickss.com/ajax/how-to-refresh-a-div-using-ajax/

Related

How to invoke PHP file in AJAX/JavaScript?

I have this code that GET the php file using an AJAX method. The goal is to inform the user if the movie table is empty or not. If the table is empty, it will display a confirm box that will ask if the user wants to add movies or not?
Here's my index.php file:
Movies
Here's my moviestbl.php:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
?>
<script language="JavaScript">
var option = confirm("No Movies found. Add Movies now?");
if(option ==true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
}
else{
//do nothing. return to current window.
}
</script>
<?php
}
?>
And finally, here's my AJAX file.
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
</script>
When I click the link, it is not doing or displaying anything. need help. thanks.
You will need to get the data from server using an ajax request , the response could be in JSON format.
Suggestions .
use jQuery and $.ajax - for pulling data from server
on getting the response - do the confirm and switch window
You can structure the logic to handle specific logics at client & server
PHP : logic on server could beCreate and interface for responding with JSON result for status of entries on movie table. your current query should work fine.
Javascript: Make use of the interface defined on php to to query data and make use of the 'confirm' javascript to do the switching.
Right now if you change
Movies
to
Movies
You should see it working with page reloads and redirects.
This will probably work better:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
echo "empty";
}
?>
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
if(XMLHttpRequestObject.responseText === "empty"){
var option = confirm("No Movies found. Add Movies now?");
if(option == true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
} else{
//do nothing. return to current window.
}
}
}
}
XMLHttpRequestObject.send(null);
}
</script>
I was able to make the code run now. Thanks to Firebug and coffee. The anchor tag is the problem. I don't know why, but when I used the img instead, it worked.
<img alt="movies" style="cursor:hand;cursor:pointer;" onclick="checkMovieTbl('/movies/ajaxphp/moviestbl.php')"/>
The PHP Script file:
<?php
//fetch the data from the table movies
include '../phpfunc/connect.php';
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
$json = json_encode($countRows);
if($json == 0){
echo $json;
}
?>
And lastly, the AJAX file.
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTbl(url){
//if not false
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("GET", url, false); //not sync
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var response = XMLHttpRequestObject.responseText;
//alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
if(response==0){
//execute something here
}
}
else{
alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
}
}
XMLHttpRequestObject.send();
}
}
Thanks to everyone who answered my questions and helped me. Chiao!

How to pass javascript variable to php in html? (wikipedia parsing)

Hi I'm trying to pass a javascript variable called $url to a function in php all located in the same html file. The logic here is that there is a text box and the user inputs a species and we call the wikipedia api to check if the input has a wikipedia page if it does I parse the page and bring the species info up, everything works independently 100% but I cant seem to connect them. However I cant get javascript to pass the url to the php function below. and innerHTML the php function with the url which is suppose to render the parsed species info. The error I get is that from the get go I just get the php function spit out with nothing.
Enter a species here : [text box here]
find('table.infobox'); foreach($html->find('img') as $element) { $image[]= $element; } Print $image[1]; $data = array(); foreach($table[0]->find('tr') as $row) { $td = $row->find('> td'); if (count($td) == 2) { $name = $td[0]->innertext; $td = $td[1]->find('a'); $text = $td[0]->innertext; $data[$name] = $text; } } print ""; foreach($data as $value => $before ) { print ""; } print "
$value $before
"; } ?>
Here is my attempt so far, I call the javascript and check if a link is found and call the parse function to innerthml out in the result div
<?php
//call the javascript
//if link found
//send ajax url variable to php function
//ajax call the function innerhtml in the result div
//We check if we have the param within the page call
$theDeletenode = false;
if(isset($_POST['deletenode']))
$theDeletenode = $_POST['deletenode'];
if($theDeletenode)
{
//The param 'deletenode' is given, so we juste have to call the php function "parse", to return the value
parse($theDeletenode);
}else
{
// No parametre, so we echo the javascript, and the form (without the quote and \n, it's much better)
?>
Here is the start of my html, the text box is connected to javascript which called the wikipedia api to check if the input has a wikipedia page.
<html><head>
<script type="text/javascript">
// create and return an XMLHttpRequest object
function createRequest() {
var ajaxRequest; // the xmlrequest object
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}; // end of createRequest
var spellcheck = function(data){
var found=false;var url='';
var text=data[0];
if(text!=document.getElementById('spellcheckinput').value) return;
for(i=0;i<data[1].length;i++)
{
if(text.toLowerCase()==data[1][i].toLowerCase())
{found=true;
url='http://en.wikipedia.org/wiki/'+text;
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';
}
}
if(!found)
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';
};
var requestone = createRequest();
var getjs= function(value)
{
if(!value) return;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck'; // this is the variable I want to pass
document.getElementById('spellcheckresult').innerHTML='Checking ...';
var elem=document.createElement('script');
elem.setAttribute('src',url);
elem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(elem);
// Ajax call to this page, this time with the 'deletenode' parameter
var vars = "url=" + encodeURIComponent(url);
requestone.open("POST", "parser.php", true); // parser.php : the name of this current page
requestone.onreadystatechange = handleRequest; // function to handle the response
requestone.send(vars);
};
function handleRequest()
{
//here we handle the php page response by echoing de result of the php page (normally the result of the parse function)
try{
if(requestone.readyState == 4 && requestone.status == 200)
document.getElementById('resultdiv').innerHTML= requestone.responseText;
} catch (e) {
//Wrong server answer...
}
};
</script>
</head>
<body>
<form action="#" method="get" onsubmit="return false">
<p>Enter a species here : <input id="spellcheckinput" onkeyup="getjs (this.value);" type="text">
<span id="spellcheckresult"></span></p>
</form>
<div id=resultdiv></div>
</body>
</html>
Here is my parse function which recieves a variable called url which is the validated wikipedia page and then it parses it for species info, this tested and it works but I cant get it to innerhtml this function along with the validated wikipedia url.
<?php
}
function parse($url){
print $url;
$html = file_get_html('http://en.wikipedia.org/wiki/Beaver');
$table = $html->find('table.infobox');
foreach($html->find('img') as $element)
{
$image[]= $element;
}
Print $image[1];
$data = array();
foreach($table[0]->find('tr') as $row)
{
$td = $row->find('> td');
if (count($td) == 2)
{
$name = $td[0]->innertext;
$td = $td[1]->find('a');
$text = $td[0]->innertext;
$data[$name] = $text;
}
}
print "<table class='infobox' style='text-align: left; width: 200px; font-size: 100%'>";
foreach($data as $value => $before )
{
print "<tr><td>$value</td><td>$before</td></tr>";
}
print "</table>";
}
?>
This question has many related answers 1234
If it helps, here is some JavaScript:
var form = document.createElement("form");
var input = document.createElement("input");
form.method="{post/get}";
form.action="{page}";
input.name="{name}";
input.value="{value}";
form.appendChild(input);
form.submit();

Get data from 3 dropdown menus and populate a 4 one from db based on that 3 parameters

I need to know what is wrong. The PHP doesn't return anything. I think the variables don't get on the PHP file. Please help me to find out what goes wrong.
<?php
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$an=$_POST['an'];
$fac=$_POST['fac'];
$uni=$_POST['uni'];
$result1 = mysql_query("SELECT * FROM drv_uni_$uni WHERE an='$an'");
while($row = mysql_fetch_array($result1)){
$display_string = "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>";
}
echo $display_string;
?>
Javascript
function getValFromDb() {
var valoare_selectata_uni = document.getElementById('category').value;
var valoare_selectata_fac = document.getElementById('subcategory').value;
var valoare_selectata_an = document.getElementById('an').value;
var url = "modules/mod_data/tmpl/script.php";
var params = 'uni=' + valoare_selectata_uni +
'&fac=' + valoare_selectata_fac +
'&an=' + valoare_selectata_an;
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", url, false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4 && AJAX.status == 200) {
var answer = AJAX.responseText;
document.getElementById('materie').innerHTML = answer;
}
};
AJAX.send(params);
}
}
You can debug the code using below few methods.
You can 1st print_r($result1) and see whether your SQL returns the results you want. If not try working on the query.
$display_string = "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>"; is wrong you should have a it like below. $display_string .= "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>";. You are missing .=
if had static variables and included on the main it shows good. Rather than using $_POST use Joomla's way of retrieving POST data JRequest::getVar('an');. Read more
let me know the results I might be able to help you.

How to use AJAX in IE

i'm using IE and I need to do a simple AJAX that will display a table with values from the database once a dropdown has been changed.
Here is my script:
<script type="text/javascript">
function getXML()
{
var req;
try {
req = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
req = null;
}
}
}
if (!req){
return null;
} else {
return req;
}
}
function filter(month, year)
{
if(getXML()){
var xmlhttp = getXML();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mandayTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/filterMandays.php?m="+month+"&y="+year,true);
xmlhttp.send();
} else {
alert("Error initializing XMLHttpRequest!");
}
}
</script>
and here is my ajax php
<?php
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';"; //employee_details WHERE approver = 0"
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
/while($rows = $res->FetchRow())
for($i=0;$i<5;$i++)
{
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows[5];
$lastname = $rows[6];
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
THe problem is that on the first "ONCHANGE" it does not do anything.
on the 2nd "ONCHANGE" the headers of the table in the php code is the only one that's being echoed.
I alsoi tried doing it without the query and changing the loop into for($i=0;$i<5;$i++) and changed the qvalues to be displayed into "1" but still it does noty go into the loo[ and display it.
what seems to be the problem? :(
Start here : https://developer.mozilla.org/en/AJAX/Getting_Started , Mozilla explains the correct way to do this across browsers. Later, you may consider jQuery for cross-browser compatibility once you've learned the basics
Download and use jQuery for your website: http://docs.jquery.com/Downloading_jQuery#Download_jQuery
And then your code will be something like this:
$('.mydropdown').change(function(){
//get values for month, year
$.ajax({
url: "ajax/filterMandays.php?m="+month+"&y="+year,
type: "GET",
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});

How to get time from server using ajax?

I am trying to create a website like penny auction how to display the count down time?
i tried that using ajax, but sometimes it swallow one or two seconds, it shows seconds like 10,9,7,6,3... i mean it doesn't show the proper count down time.. please help me to solve this problem
here is my code
<?php
#session_start();
include "includes/common.php";
include_once "includes/classes/class.Auction.php";
$objAuction = new Auction();
$result=$objAuction -> getStatus();
echo $result;
?>
//ajax code
function getStatusOne(pId)
{
var strURL="get_status_one.php?pId="+pId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
//alert(req.responseText);
var result= req.responseText.substr(1).split("|");
for (var x = 0; x < result.length; x++)
{
var resultN=result[x].split(",");
var prId=resultN[0];
var temp=resultN[1];
var sec=parseInt(temp);
var price=resultN[2];
//alert(prId+' '+temp+' '+price);
var mem=resultN[3];
var img=resultN[4];
var autobid=resultN[5];
if(img=='') {
img='images/profile/no_image.jpg'
}
if(!price)
{
price='0.00';
}
if(!mem)
{
mem='No Bidders Yet';
}
if(document.getElementById("bid_price"+prId))
{
document.getElementById("bid_price"+prId).innerHTML='$'+price;
document.getElementById("bidder_name"+prId).innerHTML=mem;
document.getElementById("userimg").src=img;
document.getElementById("bid_rate").innerHtml=autobid;
if(sec<= -1)
{
sold(prId);
if(document.getElementById('end'+pId))
{
document.getElementById('end'+pId).style.display="block";
}
if(document.getElementById('div_bid_image'))
{
document.getElementById('div_bid_image').style.display="none";
}
if(document.getElementById('clsBidB'+pId))
{
document.getElementById('clsBidB'+pId).style.display="none";
}
}
else {
if(document.getElementById('div_bid_image').style.display == "none")
{
document.getElementById('div_bid_image').style.display="block";
}
if(sec >=0)
{
SetCountdownText(sec,"div_timer"+prId,prId);
}
}
}
}
}
else
{
//alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//php code to calculate time
function getStatus()
{
$selProd="select a.pdt_id, unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."') as seconds, b.bid_price,c.uname from tbl_products a left join tbl_auction b on a.pdt_id=b.product_id left join tbl_members c on b.member_id=c.member_id where(select unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."'))>= 0 ";
if($this->ExecuteQuery($selProd,"norows") > 0)
{
$auctionArr=$this->ExecuteQuery($selProd,"select");
$auctionName=$this->array2str($auctionArr);
}
return $auctionName;
}
function array2str($array,$level=1)
{
$str = array();
foreach($array as $key=>$value) {
if(is_int($key))
{
$nkey = $key;
$nvalue = is_array($value)?'|'.$this->array2str( $value ) : $value;
$str[] = $nvalue;
}
}
return implode(',',$str);
}
try this
<?php
$target = mktime(0, 0, 0, 14, 07, 2011) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
print "Our event will occur in $days days";
?>
Assuming you have something like a DIV with the ID "countdown" (to display the countdown in):
Example JavaScript (assumes use of jQuery - recommended):
(function(jQuery) {
updateCountdown("countdown"); // Call on page load
var countdown = setInterval('updateCountdown("countdown")', 1000); // Update countdown every second
})(jQuery);
function updateCountdown(elementId) {
jQuery.ajax({
url: "/ajax/countdown.php?auctionId=123",
type: "GET",
dataType: "json",
success: function(response) {
// Insert value into target element
jQuery("#"+elementId).html(response["timeRemaining"]);
// Stop countdown when complete
if (response["countdownComplete"] == true)
clearInterval(countdown);
}
});
}
Example PHP script (assumed to be at /ajax/countdown.php by the above JavaScript):
<? php
/* Insert your own logic here */
$response["timeRemaining"] = "5 seconds";
$response["countdownComplete"] = false; // Set to true when countdown complete
echo json_encode(response);
?>
I'd recommend doing all the calculation server side (in PHP) as it has really excellent time/date handling (with lots of built in methods) and requires less code to implement overall.
Have a PHP page echo out the countdown time. And then use something like jQuery's AJAX HTTP Request for that page and populate the response in a DOM element somewhere.
Why do you need Ajax to display the countdown time? Why can't you just display it when the page loads along with the rest of the data?

Categories