Ajax Returns Random Values? - php

I am working on a simple AJAX page. when the page loads, it should take the result from the PHP page and display it in the text box. If the result is "1" (which it should be), then it should pop up an alert saying "Ready."
Main page's code (t1_wait.php):
<html><head><title>Waiting...</title></head><body>
<script type="text/javascript">
function update(id)
{
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else if (window.ActiveXObject){
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.responseText=="1")
alert("Ready!");
}
document.myForm.status.value=xmlhttp.responseText;
}
}
var requesturl = "t1_checkMatch.php?id="+id;
xmlhttp.open("GET",requesturl,true);
xmlhttp.send(null);
// delay for 1 sec
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < 1000);
}
<?php
echo "update(".$_GET['id'].");";
?>
</script>
<form name="myForm">
Status: <input type="text" name="status" />
</form>
</body></html>
The PHP page being called out to (t1_checkMatch.php) (all db info replaced with *****):
<?php
$db_user = "*****";
$db_pass = "*****";
$db_name = "*****";
mysql_connect(localhost,$db_user,$db_pass);
#mysql_select_db($db_name) or die("Unable to select database");
$match_id = $_GET['id'];
$match_info = mysql_query("SELECT * FROM ***** WHERE id=".$match_id);
if(mysql_result($match_info,0,"usr2")==-1){
echo "1";
}else{
echo "0";
}
?>
When I go to the t1_wait.php?id=16 (the main page passing id=16 via GET), it should send a request to t1_checkMatch.php?id=16, which returns (yes, I checked) 1. This should trigger an alert saying "Ready" and cause 1 to appear in the text box, but neither of these things happen. The text box is blank.
What's wrong? Thanks!

I believe the problem you are running into is due to a typo
xmlhttp.responceText
Really should be
xmlhttp.responseText
-- Update
It also appears that you are missing a {:
if(xmlhttp.responseText=="1")
alert("Ready!");
}
Should be
if(xmlhttp.responseText=="1"){
alert("Ready!");
}

You have a spelling mistake:
if(xmlhttp.responceText=="1")
should be:
if(xmlhttp.responseText=="1")
(you spelled response incorrectly)

Ok. I figured it out, but I don't know what I did. I did have a typo, but that isn't the problem. The PHP code is the same, here is the main page code:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function update(id){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.responseText.indexOf("1")!=-1){
document.myForm.status.value = "Ready!";
window.location = "t1_game.php?id="+id;
}else{
document.myForm.status.value = "Waiting..."
update(id);
}
}
}
ajaxRequest.open("GET", "t1_checkMatch.php?id="+id, true);
ajaxRequest.send(null);
}
<?php
echo "update(".$_GET["id"].");"
?>
//-->
</script>
<form name='myForm'>
Status: <input type='text' name='status' />
</form>
</body>
</html>

Related

jQuery data sent from PHP is not the correct format?

I am using jQuery to send a part number from one php file to another.
The part number is received correctly in the destination php file, but when when I try to use it, it does not work.
Here is the strange thing: To test,when I use $mpn=STA-12 (or any other value that exists in table2), in destination php file, the connection is established and the relevant data is extracted, BUT when THE SAME DATA is fetched, it does not work
Here is the destination PHP file:
<?php
$row['mpn'] = $_GET['q'];
include("order/connection.php");
echo "mpn is here : ".$row['mpn']; // It displays STA-12 but doesn't data get fetched!
$mpn=$row['mpn'];
//$mpn="STA-12"; // *** When I actually put this line in, it all works ***
$stmt = $pd->prepare("SELECT * FROM table2 WHERE part_number = :part_number " );
//$stmt->execute(array());
$stmt->execute(array(':part_number' => $mpn));
$row = $stmt->fetch(PDO::FETCH_BOTH);
//... rest of the code
?>
This jQuery script copied from W3:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","serv.reply3.3.php?q="+str,true);
xmlhttp.send();
}
}
And this is where it is called from:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Choose</option>
<option value=" <?php echo $row["mpn"]; ?> ">items</option>
</select>
</form>
The problem is finally solved.
Since the code was copied from another example, the jQuery variable sent over, contained some EXTRA information that when ECHO'ed didn't show.
echo "mpn is here : ".$row['mpn']; that displayed STA-12, actually contained ' string(6) " STA-12" ', which was discovered by doing:
var_dump( $row['mpn']).
This had my head scratching for days.

Display value from text file on website

I am using AJAX to track the number of clicks of a button on my site and I would like to display that value on the page as well. Currently the tracking is working great and the number of clicks is being printed to a document called clicks.txt and I was wondering how I could go about reading the value from that text file and printing it to the page.
I tried searching SO and Google for an answer, but I guess I can't think of how to word it properly because the answers I have found so far have been unrelated to what I'm trying to do.
Here is the AJAX included in index.php
<script type="text/javascript">
function getXMLHttp()
{
var xmlHttp
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "counter.php", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
Here is the external PHP(counter.php) I am using to track the button clicks:
<?php
$clicks = file_get_contents("clicks.txt");
$clicks++;
$fp = fopen("clicks.txt", "w+");
while ( !flock($fp, LOCK_EX) ) {
usleep(500000); // Delay half a second
}
fwrite($fp, $clicks);
fclose($fp);
flock($fp, LOCK_UN);
?>
Thanks in advance!
$clicks = file_get_contents("clicks.txt");
echo $clicks;
If the page that the button exists on is a .PHP file, you can embed code similar to this directly on the page where you want it to be displayed:
<?php
$clicks = file_get_contents("clicks.txt");
echo $clicks;
?>

Google Maps API V3 not showing map

Okay so I have a PHP script which handles file uploads, KML files specifically, extracts the center point and the location of the uploaded file, saves these details in text files, and then loads another page via "header". This other page then uses AJAX calls to set variable names as gathered from the text files, for the location of the KML file and the center point, in order to call the Google Maps API to show the KML layer upon a map.
That is what is supposed to happen, but instead nothing appears. I browse for my KML file, hit the upload button, and a blank page is shown. When I check my server, the file as been uploaded and the relevant details written into their respective text files, so obviously something is going wrong when I try to call the Google Maps API.
PHP upload and file info saving:
<?php
//Check that we have a file
if((!empty($_FILES["UploadedFile"])) && ($_FILES['UploadedFile']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 3Mb
$filename = basename($_FILES['UploadedFile']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "kml") && ($_FILES["UploadedFile"]["size"] < 3145728)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/kml/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['UploadedFile']['tmp_name'],$newname))) {
findCenter($newname);
saveName($newname);
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["UploadedFile"]["name"]." already exists";
}
} else {
echo "Error: Only .kml files under 3Mb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
function findCenter($file) {
$kmlContent = file_get_contents($file);
$startName = "#sh_green-circle";
$endName = "#sh_red-circle";
$startCoords = getCoords($kmlContent, $startName);
$endCoords = getCoords($kmlContent, $endName);
$startLat = substr($startCoords, strrpos($startCoords, ',') +1);
$startLong = substr($startCoords, 0, strrpos($startCoords, ','));
$endLat = substr($endCoords, strrpos($endCoords, ',') +1);
$endLong = substr($endCoords, 0, strrpos($endCoords, ','));
$midLat = ($startLat+$endLat)/2;
$midLong = ($startLong+$endLong)/2;
$midCoord = "$midLat,$midLong";
$saveCenter = "kmlcenter.txt";
$fh = fopen($saveCenter, 'w') or die ("Can't create file");
$stringData = $midCoord;
fwrite($fh, $stringData);
fclose($fh);
}
function getCoords($kml, $name) {
$startSearch = strpos($kml, $name);
$midSearch = strpos($kml, "<coordinates>", $startSearch+1);
$endSearch = strpos($kml, "</coordinates>", $midSearch+1);
$longlat = substr($kml, $midSearch+13, $endSearch-($midSearch+13));
return $longlat;
}
function saveName($filename) {
$saveFile = "kmlfilename.txt";
$fh = fopen($saveFile, 'w') or die("Can't create file");
$stringData = "$filename";
fwrite($fh, $stringData);
fclose($fh);
header("Location: initgmaps.html");
}
?>
Map intitialisation:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
<script type="text/javascript">
function initialize() {
var kmlName = getName()
var kmlCoords = getCoords()
var mapcenter = new google.maps.LatLng(kmlCoords);
var myOptions = {
zoom: 11,
center: mapcenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("infoArea"), myOptions);
var kmlLayer = new google.maps.KmlLayer(kmlName);
kmlLayer.setMap(map);
}
</script>
Relevant AJAX functions:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getName(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlName;
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 does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlName = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlfilename.txt", false);
ajaxRequest.send(null);
}
//-->
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getCoords(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlCoords;
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 does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlCoords = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlcenter.txt", false);
ajaxRequest.send(null);
}
//-->
And of course in the body of initgmaps.html I have:
onload="initialize()"
infoArea is the ID for my inline frame.
Can anyone see why it doesn't load? I'm completely and utterly new to web development, learning as I go, so sorry if the code is terrible and I'm sure I've made some obvious errors. Many thanks.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
You have missed an ampersand here... Should be:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[[YOUR-GMAPS-KEY]]&sensor=false"></script>
(Where [[YOUR-GMAPS-KEY]] is your Google Maps Key - "AIzaSyB8P7CzxiwQFf-RdK9QV...".)
Try adding an ampersand '&' after your key and before the sensor=false parameter.
Additionally
var kmlCoords = getCoords()
is javascript, but function getCoords() is PHP. Javascript cannot execute a PHP function.
the error might be caused by not following this format:
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
see, after "YOUR_API_KEY" there shouldn't be "sensor=false".
try it. hope it works.

How to prevent the page from scrolling after an ajax request (return false not working or maybe in the wrong palce)

I want to display a tree with information about the Catalogue of Life which includes the Kingdom, phylum, order, etc information. I'm using ajax/php to interact with a mySQL database, while using javascript to display and output the information. I have finally completed the things I wanted it to do: expand and collapse on clicking, load only once, etc. But everytime something is clicked below the scroll limit, it bounces back to the top of the page. I researched this and saw something about including 'return false' in the function or the tag, but this did not solve the problem. Am I just putting it in the wrong place? Thanks for your help...
Here is the code: in its php/javascript goodness...
<?php
include ('includes/functions.php');
$connection=connectdb();
$result=runquery('
SELECT scientific_name_element.name_element as shortname ,taxon_name_element.taxon_id as taxonid
FROM taxon_name_element
LEFT JOIN scientific_name_element ON taxon_name_element.scientific_name_element_id = scientific_name_element.id
LEFT JOIN taxon ON taxon_name_element.taxon_id = taxon.id
LEFT JOIN taxonomic_rank ON taxonomic_rank.id = taxon.taxonomic_rank_id
LEFT JOIN taxon_name_element AS tne ON taxon_name_element.parent_id = tne.taxon_id
LEFT JOIN scientific_name_element AS sne ON sne.id = tne.scientific_name_element_id
LEFT JOIN taxon AS tax ON tax.id = tne.taxon_id
LEFT JOIN taxonomic_rank AS tr ON tr.id = tax.taxonomic_rank_id
WHERE taxon_name_element.parent_id is NULL');
set_time_limit(0);
ini_set('max_execution_time',0);
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
function load_children(id){
if(document.getElementById(id).active != 'true'){
if(document.getElementById(id).loaded != 'true'){
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()
{//actual stuff
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{//change the text
this.active='true'
//document.getElementById(id).innerHTML = xmlhttp.responseText;
var oNewNode = document.createElement("ul");
document.getElementById(id).appendChild(oNewNode);
document.getElementById(id).active = 'true';
document.getElementById(id).loaded = 'true';
oNewNode.innerHTML="<i>"+xmlhttp.responseText+document.getElementById(id).active+"</i>";
}
}
xmlhttp.open("GET","new.php?id="+id,true);
xmlhttp.send(false);
}else{
$("#"+id).children().children().show(); document.getElementById(id).active = 'true'}}else{ $("#"+id).children().children().hide();
document.getElementById(id).active = 'false';
}return false;}
</script>
</head>
<body>
<?php
echo "<ul>";
while($taxon_name_element = mysql_fetch_array($result)){
echo "
<li id=\"{$taxon_name_element['taxonid']}\" style=\"display:block;\">{$taxon_name_element['shortname']}</li>
";}
echo "</ul></body></html>";
?>
You were missing a closing parenthesis - if popped it in with a comment where I think you were wanting it. If JS has an error it generally won't execute, and instead it'll fall back to the non JS (ie, the return false wont fire because of the error). Were you getting an actual error when running this? The console is a good friend when you're debugging JS.
Formatting your code like I have below will also help to identify any missing elements more easily.
function load_children(id)
{
if(document.getElementById(id).active != 'true')
{
if(document.getElementById(id).loaded != 'true')
{
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()
{
//actual stuff
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//change the text
this.active='true'
//document.getElementById(id).innerHTML = xmlhttp.responseText;
var oNewNode = document.createElement("ul");
document.getElementById(id).appendChild(oNewNode);
document.getElementById(id).active = 'true';
document.getElementById(id).loaded = 'true';
oNewNode.innerHTML="<i>"+xmlhttp.responseText+document.getElementById(id).active+"</i>";
}
}
xmlhttp.open("GET","new.php?id="+id,true);
xmlhttp.send(false);
} // This was missing - were you getting an error?
}
else
{
$("#"+id).children().children().show(); document.getElementById(id).active = 'true'}
}
else
{
$("#"+id).children().children().hide();
document.getElementById(id).active = 'false';
}
return false;
}
When you're done checking and if everything is ok, take a look at: http://api.jquery.com/jQuery.get/ - the example's are at the bottom.

random quote generator with php, ajax and mysql

i've tried using this code and this to make a random quote generator, but it doesn't display anything. my questions are:
what is wrong with my code?
in the above tut, the quote is generated on a button click, i'd like
a random quote to be displayed every
30 mins automatically. how do i do
this?
////////////////////////
quote.html:
<!DOCTYPE html>
<script src="ajax.js" type="text/javascript"></script>
<body>
<!–create the div for the quotes land–>
<div id="quote"><strong>this</strong></div>
<div><a style="cursor:pointer" onclick="run_query();">Next quote …</a></div>
</body>
</html>
/////////////////////
quote.php:
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
$result = mysql_query("select * from quotes limit $rand, 1");
$row = mysql_fetch_array($result);
$randomOutput = $row['storedText'];
echo '<p>' . $randomOutput . '</p>';
////////////
ajax.js:
var xmlHttp
function run_query() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("This browser does not support HTTP Request");
return;
} // end if
var url="quote.php";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} //end function
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("quote").innerHTML=xmlHttp.responseText;
} //end if
} //end function
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// For these browsers: Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//For Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
} //end function
Try to print the values for $max,$rand and $result. You can use print_r to get more info from the php page.
Run the quote.php on browser to see if you get an output.
Then get to ajax to debug.
You can use a timer in ajax to automate your requests for every 30 mins or so. use javascript's settimeout function for this.
HTH

Categories