I'm not very skilled in web developing by the moment but i've managed to create a web application with PHP that queries a MYSQL Database and shows data in HTML.
I would like to check if the table has changed using a timestamp field that I already created and that updates on every insertion. Comparing two timestamps (the previous and the current) is the key,
but I don't handle javascript that much.
How can I pass a parameter to my hastablechanged.php file (the previous timestamp) and simply return a flag (1: changed, 0: not changed) to javascript?
and... how would be a basic javascript function to run a timer and call hastablechanged.php posting old_timestamp and receiving the flag and then update the div?
I've been googling but the solutions I have found are very complex and I know i just need a javascript function that I don't find out how to write.
This is hastablechanged.php:
<?php
include 'config.php';
include 'opendb.php';
$table = "data_table";
$query_timestamp = "select timestamp from {$table} where id = 0;";
$timestamp = mysql_query("{$query_timestamp}");
if (!$timestamp) {
die("query failed");
}
$row_timestamp = mysql_fetch_array($timestamp);
echo $row_timestamp['timestamp'];
?>
And this is my index.php
<!DOCTYPE HTML PUBLIC>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>Data values</title>
</head>
<body>
<div id=data>
<? include("table.php");?>
</div>
</body>
</html>
where "table.php" is the php code that selects the data and displays it drawing a html table.
I would thank a lot any help, as I'm stuck in this issue for finishing my degree project
You need Ajax and setInterval.
Here is how SetInterval works
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
SetInterval basically just tells the browser to call a javascript function every x milliseconds.
Here is a few Ajax Examples
http://www.w3schools.com/Ajax/ajax_examples.asp
Ajax is basically a way for javascript to request a page and get its contents without reloading the page. In the example below it tries to create an xmlhttprequest for all the browsers (sadly it's done like this) and then sends in the request. We define state_change as the function to be called when we get a reply back. In this example it just takes the response and displays it, but you can do whatever you want with that.
Below is a modified example. It should work.
<html><head>
<script type="text/javascript">
var xmlhttp;
function loadPage()
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET","hastablechanged.php?tablename=awesometable",true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = "OK"
document.getElementById('A1').innerHTML=xmlhttp.responseText;
}
else
{
alert("Problem retrieving ata:" + xmlhttp.statusText);
}
}
}
</script>
</head>
<body onLoad="setInterval('loadPage()', 10000)">
<p><b>Status:</b>
<span id="A1"></span>
</p>
<button onclick="loadPage()">Check Updates</button>
</body>
</html>
Just to be clear: you don't have to use ajax. Just reloading the page on regular interval will give you what you want. BUT if you want the application to be smooth - then you'll have to dig into AJAX as outlined in the other answers.
-CF
I finally figured out how to do it. Posting it so it can be useful for anybody.
It's a combination of php and javacript where:
php file return_timestamp.php simply returns the timestamp of a row with ID=0 (no real ID, it simply updates its timestamp in each insertion with a trigger)
javascript compares the received timestamp with the one previously received (the very first one is set to 0 so it updates the div in the beginning)
so:
javascript code which is the important thing (i assume you guys can code php retrieving data from mysql):
<script type="text/javascript">
$(document).ready(function() {
$timestamp1='0';
var refreshId = setInterval(function() {
$.get(('return_timestamp.php', function(data) {
$timestamp2 = data; } )
if ( $timestamp2 != $timestamp1 ) {
$('#data').load('data.php');
$timestamp1 = $timestamp2; }
}, 1000);
});
</script>
Hope it helps, and thanks as well for YOUR help!
Related
I am building an application. The main purpose of my work is to change an object in the php page according to the database entries.
I have one php file ajax.php. It will query the database table and return the value to my other file main.php
The main page uses ajax to query the database. And depending on the database return it will show some images to some positions in the php page.
Example: if the return value from the database query is 2: it will show image at (x1,y1) position and it will blink, and open one small window.
If the return value from the database query is 3: it will show image at (x2,y2) position and it will blink and open one window2
I am not being able to pass the ajax query value to my php portion. Only if I want to ptint the value in then it is possible.
But I want to do something like
if ($returnvalue == 1)
window.open("window1");
blink_image1();
if ($returnvalue == 2)
window.open("window2");
blink_image2();
Please help me.
Following are the code snippet:
ajax.php
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','user','password','database');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql='SELECT id FROM table_name order by timedate asc' ;
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$value = $row['id'];
}
echo $value;
mysqli_close($con);
?>
main.php
<html>
<head>
<IMG STYLE="position:absolute; TOP:135px; LEFT:350px; WIDTH:900px; HEIGHT:500px"SRC="testrect1.php"/>
<script>
var refreshtime=10000;
function showUser(str)
{
setTimeout(showUser,refreshtime);
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
var msg=document.getElementById("txtHint");
}
}
xmlhttp.open("GET","ajax.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body onload="showUser(this.value)">
<div id="txtHint"></p> </div>
<?php
/*
I need the return value here.. So that I can do
if ($return_val == 1)
Blink_image1();
open_window1();
.
if ($return_val == 2)
Blink_image2();
open_window2();
*/
?>
</body>
</html>
Please help me..
It looks like you're trying to pass back the AJAX request to the PHP file as the page is still loading. That will not work. PHP executes on the server, but javascript executes in the user's browser. That means you can't have javascript generated by a file send back information to the file that's generating it, because there is no way for the result to get there.
Think of it like sending a boat across a river: if you get to the other side, you may notice that you don't have a rope to tie the boat up with. However, you can't then add the rope to the boat, because it's already there with you; you need to either plan ahead ("I should really bring a rope with me") or send for another boat to bring you a rope.
What you can do instead is one of three things, in the order in which I would recommend them:
Since you want the information displayed at pageload anyway, you can simply put the code in the same page as you want it to appear. So in your code, where you put your comment about "here's where I need this to happen," put your database call and logic there, rather than in a separate ajax.php file.
Put the logic for what to display inside ajax.php, so that instead of sending the number to the browser, you're sending what it is you want to display.
Put the logic for what to display inside your javascript function.
Good evening. I am creating a game using CANVAS, PHP, MySQL and AJAX. It is a very simple game: it consists of a board, 8 squares tall and 8 squares long (like that of a Chessboard). The user is supposed to click any of the squares, and the square he/she clicked is to be stored in a DataBase as (xpos, ypos). Of course, the DataBase is stored in the server-side and the html game is running on the client-side, so I need AJAX to interact between javascript and php. I did this job and everything worked fine.
My problem arises when I try to load the Board. Imagine we have in our DataBase the next data:
(Row) ... (xpos) ... (ypos)
1 1 2
2 3 2
3 6 5
When the user opens the Game, I need it to Load this positions onto the Board by retrieving the (xpos, ypos) data from the DataBase. The code I tried looks like this:
Game.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basic Game</title></head>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded () {
requestXMLLoadGems();
}
function requestXMLLoadGems() {
var xmlhttp;
if ( window.XMLHttpRequest ) { // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","download_gems.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
mycoords=xmlhttp.responseText;
document.write(mycoords);
}
}
xmlhttp.send(null);
}
</script>
<body></body>
</html>
The server-side file "download_gems" looks like this:
download_gems.php
<?php
// Open a MySQL connection
$dbinfo = 'mysql:host=localhost;dbname=mydb';
$user = 'root';
$pass = '';
$link = new PDO($dbinfo, $user, $pass) or die('Error connecting database');
// Create and execute a MySQL query
$sql = "SELECT xpos,ypos FROM board";
foreach($link->query($sql) as $row) {
$entries[]=array($row['xpos'], $row['ypos']);
}
print_r($entries);
?>
Everything works fine. Except that I need to retrieve Numerical Data (xpos, ypos), and not String data. My question is how can I retrieve NUMERICAL Data using:
xmlhttp.responseText;
I can't find the answer anywhere!
I would appreciate any help. Thank you very much.
Instead of print_r(), use json_encode() and send the output with a JSON content type header. Then use a JSON parser on the client side. E.g. jQuery auto-converts valid JSON to a JavaScript object for you if you use it's ajax functionality.
Unrelated: you will not be able (nor would you want) to use document.write(), for this (or just about anything!).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
pass php variable to javascript
I want to compare the click count(s) clicked by the users with the data saved in database.
I am not sure how to proceed to pass the value of the HTML "clicks" to compare with "counts" in PHP.
<html>
<script type="text/javascript">
var count = 0;
function countClicks()
{
count = count + 1;
document.getElementById("clicks").innerHTML = count;
}
</script>
<?php
if(empty($counts)){
?>
<script type="text/javascript">
alert("Count is empty!!");
</script>
<?php
} else {
$data = mysql_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
$info = mysql_fetch_array($data);
//compare $data with the clicks
echo 'same!';
}
?>
<body>
Count Clicks
<input type="button" onclick=countClicks() value="Click"/>
<p id="clicks">0</p>
</body>
</html>
You are using PHP and Javascript in the wrong way. PHP is a serverside language. which means it runs before the page even loaded on the browser.
You will have to create a javascript click counter and put its values into a hidden formfield. Then use a submit button to send the information to the server (PHP). Then let PHP do the checks and selections from the database and return an answer.
Another solution is to use javascript AJAX, but I do recommend first trying the above.
The best way to proceed would be to make an Asynchronous JavaScript and XML call (AJAX). PHP is a server-side language, which is executed before the HTML (thus, before Javascript) is built and shown to the browser.
Therefor, the only way for Javascript to exchange variables and data with PHP is to make an AJAX call (you could always reload the page with a form submit or with session variables and cookies, but this isn't the best way to go if action is repeated too often.
IN AJAX, you can make another PHP page that will check both values and return whatever you want. The response can be stored in a Javascript variable, or even in JSON.
I suggest you to read more about AJAX and also get to know what is PHP how to use it.
Edit: After reading your comment, I decided to put a simple example down here.
Javascript (in your HTML page)
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)
{
/*Here you should do what you want.
xmlhttp.responseText is the content of your PHP answer! */
var result = xmlhttp.responseText;
//I am parsing a JSON response, which is a specific, universal language
//To exchange data without losing formatting or anything else.
result = JSON.parse(result);
/* The we use the name of our PHP array key as a property
Here it is "response" (see PHP json_encode line) */
alert(result.response);
}
}
/* Change this URL for the PHP filename. we use the GET method to send data. */
/* You should always use the POST method when sending sensitive data */
xmlhttp.open("GET","getUserClicks.php?clicks="+count+"&username="+username,true);
xmlhttp.send();
PHP (here it is the file named getUserClicks.php )
<?php
if(!isset($_GET['username']) || !isset($_GET['clicks']))
die("Error");
$username = $_GET['username'];
$jsClicks = $_GET['clicks'];
$phpClicks = null;
#I am using the mysqli class to execute the query since mysql is deprecated in PHP5.
$data = mysqli_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
while($row = mysqli_fetch_array($data))
{
$phpClicks = $row['clicks'];
}
#If your "IF" only contains one line, you don't need brackets.
#Otherwise they are needed.
if($phpClicks == null)
die("Could not get the number of clicks of the desired username");
#This is the string PHP will send to Javascript.
$response = "Same number of clicks!";
#If phpClicks is different and has the same type as jsClicks...
if($phpClicks !== $jsClicks)
{
$response = "Number of clicks changed!";
if($jsClicks > $phpClicks)
{
#Updates the number of clicks the user has done.
$mysqli_result = mysqli_query("UPDATE customerdetails SET clicks=$jsClicks WHERE customer_username='$username';");
}
}
echo json_encode(array('response'=>$response));
?>
Be sure to make some research if you see functions or methods you have no idea what they do (eg.: isset).
I have a simple HTML form which starts with a select menu where the user can select from a list of Projects. I've created a simple JSFiddle with the HTML form here:
http://jsfiddle.net/AZ4PM/
What I would like to happen is that when the user selects from the list it triggers a php script to be performed which takes the value from the ProjectNumber they have selected and passes this as a parameter, e.g. if I select Project A the URL would be:
getProjectPhases.php?projectNumber=10000
This php script will then return a new table cell which I would then like to appear as the 2nd cell in the form. It contains a new select menu with the values changing depending on the selection in the first select menu. This php page is working well manually, but I'm at the point now where I need to have it triggered when the user makes a selection from the Project Number menu.
I'm new to AJAX and would like to start with a simple example one step at a time whilst I learn. I'm happy to use jQuery if that makes things easier.
Appreciate any pointers to what the basic elements I need to include (assuming at least one js file etc).
I have something very similar that I use:
<select name="selectProject" id="selectID" onChange="showUser(this.options[selectedIndex].value)">
<?php
// Loop through and list each project
foreach ($var as $row) {
echo '<option value="'.$row['projectNumber'].'">'.$row['projectName'].'</option>';
}
?>
</select>
<label>Project Name</label>
<input id="projectName" type="text" class="span3" name="projectName">
The above just calls the showUser function with the parameter that is the projectNumber
Then below that I have:
<SCRIPT TYPE="text/javascript">
// Function to fill in form fields
function showUser(str)
{
if (str=="")
{
document.getElementById("").innerHTML="";
return;
}
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 obj = eval('(' + this.responseText + ')');
document.getElementById("projectName").value=obj.projectname;
}
}
xmlhttp.open("GET","http://url.com/ajax/"+str,true);
xmlhttp.send();
}
</SCRIPT>
This script will call the url url.com/ajax/whateverIdIsSelected
From that page, you want to do whatever you have to do with your query.
As for what to return, I have this set up to use json, which I why I have the line
var obj = eval('(' + this.responseText + ')');
this.reponseText is what is returned from the ajax page. My return call looks like this
$projectData = json_encode($project);
echo $projectData;
Where $project is an array containing your project's attributes.
I'm not very good with ajax or js, but I got this working the way I like it. Let me know if you have questions
Pass id to the option select list
<select name="ProjectNumber" id="ProjectNumber">
Then call a method having these and then parse it via Ajax call.
var pvalue = document.getElementById('ProjectNumber').value;
var url = 'getProjectPhases.php?projectNumber='+pvalue;
First you need to bind the JQuery change() Handler to your drop down menu, calling a function that starts the ajax request, have a look at the jQuery get function you need to do something like this:
$.get("getProjectPhases.php", { projectNumber: this.val() }, function(data){
//Update your output using the data var
);
where data is the output of getProjectPhases, so it might be a good idea to just output plain text and no html tags or what ever.
I am making a web page which will allow users to input and view data for different dates, and to change the date, there are two buttons, one of which will display the previous day, and one which will show the next day. I know that I can do this by submitting forms and reloading the page every time they press one of these buttons, but I would rather use javascript and not have to submit a form, but I am having troubles getting it to work. Currently, I have the two buttons, and the date stored in a PHP variable, as shown in my code below:
<script>
function init() {
<? $nutrDate = $this->parseDate(date('m/d/Y')); ?>
}
function nutrPrevDay() {
<? $nutrDate = mktime(0, 0, 0, date('m',$nutrDate), date('d',$nutrDate)-1, date('Y',$nutrDate)); ?>
alert("<? echo(date("m/d/y", $nutrDate)) ?>");
}
function nutrNextDay() {
<? $nutrDate = mktime(0, 0, 0, date('m',$nutrDate), date('d',$nutrDate)+1, date('Y',$nutrDate)); ?>
}
window.onload = init;
</script>
<p style="text-align:center; font-size:14px; color:#03F">
<button onclick="nutrPrevDay()" style="width:200px" >< Show Previous Day</button>
<? echo(date('m/d/Y', $nutrDate)) ?>
<button onclick="nutrNextDay()" style="width:200px">Show Next Day ></button>
</p>
I have the alert in the nutrPrevDay() only as debugging. What happens is when I click on the button, the alert shows that the day is correctly decreased (for example from May 17 to May 16), but only decreases one day, and not one day for every click. Also, I do not know how to make the text on the page (created by the line ) change to display the new date after a button is clicked.
So here are my questions:
1) Is it possible to dynamically change data (such as text, and in the future, SQL queries) on a page using javascript without having to reload a page when clicking on a button?
2) If possible, how can I make those changes?
3) How can I fix this so that it will increment and decrement through dates every time a button is clicked?
Q1:
Yes, it is possible, AJAX is probably what you're looking for.
Q2:
Well, first of all you have to learn that JavaScript works at client side while PHP works at server side. With that in mind, you can't expect that php scripts are executed when you click a button just because you wrote them inside javascript functions.
The most you can do is print something from a PHP script into a JavaScript script. And your script fails in that, except for the alert part. Example:
<script>
function javascriptFunction(){
// This php script, will be executed when you call your page, however $nutrDate is an assigned php variable, javascript will never know about it;
<?php $foo = 'bar'; ?>
// This will give you a javascript error because $foo is a string
var foo = <?php echo $foo; ?>;
// This is the code which will do the expected, notice the quotes.
var foo = '<?php echo $foo; ?>';
// If you have a single quote inside $foo, it will break javascript
<?php $foo = "ba'r";
var foo = '<?php echo $foo; ?>';
}
</script>
Q3:
The idea is to make an AJAX request every time your buttons click event is triggered... This is the same as saying, when you click a button, you call a javascript function which will make a request to some other page and get something from it if the request is successful. Here the example:
<script>
var current = <? echo time(); ?>;
function requestSomething(action){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
// readyState info: http://www.devguru.com/technologies/xmldom/quickref/httpRequest_readyState.html
if (xmlhttp.readyState==4 && xmlhttp.status==200){
// this is where we tell where the result will appear
document.getElementById("current").innerHTML=xmlhttp.responseText;
current = xmlhttp.responseText;
}
}
xmlhttp.open("GET","somescript.php?action="+action+'&curday='+current,true);
xmlhttp.send();
}
</script>
<p style="text-align:center; font-size:14px; color:#03F">
<button onclick="requestSomething('decrease')" style="width:200px" >< Show Previous Day</button>
<!-- this is where the result will appear -->
<span id="current"></span>
<button onclick="requestSomething('increase')" style="width:200px">Show Next Day ></button>
</p>
Now, at your somescript.php file,
<?php
if(isset($_GET['action'])){
if($_GET['action'] == 'increase'){
// your increasing day logic here
} elseif ($_GET['action'] == 'decrease'){
// decreasing logic here
} else {
// whatever...
}
}
?>
Note: This is almost written from scratch and with some copy/past from here and there, and didn't check if the code actually works... It is just a guideline...
Hope it helps.
You don't need Ajax for this. There is very little you can do with PHP that you can't do with Javascript - you should only use Ajax when you absolutely need to communicate with the server (ex: need something from the database, etc.). Even if you may be using Ajax a later point you shouldn't use it everywhere, especially when a simple script may be able to solve your problems.
As it so happens Javascript has a number of built-in date functions that are every bit as powerful as PHP's.... and if they don't do what you need out of the box you can easily write your own.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Keep it simple.