ReferenceError: test is not defined - javascript

So I'm coding a banlist for one of my game servers. I'm using javascript to load the separate PHP page's mysql query, using an ActiveXObject.
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (str==0){
document.getElementById("txtHint").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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
if(!IsNumeric(str)){
type = "name";
}
else
{
type = "id";
}
xmlhttp.open("GET","getdata.php?" + type +"="+str,true);
xmlhttp.send();
}
That handles the getting of the user's data. I also have a PHP script, on the same page, allowing users to add get requests to the page, to get the user's ban/bans quickly. That is handled by
$id = $_GET['id'];
$name = $_GET['name'];
if(isset($id)){
echo '<script> showUser('.$id.') </script>';
}elseif(isset($name)){
echo '<script> showUser('. $name .') </script>';
}
My problem comes when I attempt to use the page's name get.
When I browse to my site,
http://banlist.unityroleplay.com/minecraft/index.php?name=test
I am faced with the error of
ReferenceError: test is not defined
Any Ideas?

if(isset($id)){
echo '<script> showUser('.$id.') </script>';
}elseif(isset($name)){
echo '<script> showUser('. $name .') </script>';
}
this code is trying execute
<script>showUser(test)</script>
and javascript understanding it as test variable. But you must do it as
<script>showUser("test")</script>
So, you must change your code as follows:
if(isset($id)){
echo '<script> showUser("'.$id.'") </script>';
}elseif(isset($name)){
echo '<script> showUser("'. $name .'") </script>';
}

Related

Passing a string variable through ajax

The variable is passed through ajax and it is a database name. When the link is clicked it's supposed to retrieve a data from the the database. the link and the variable is on the same page. Here is the code for the link:
$x = strval($_GET['x']);
echo ''.$seatid.'';
The $x variable contains the table name of the database. And here is the code for ajax:
function showInformation(str)
{
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("txtInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinfo.php?x="+str,true);
xmlhttp.send();
}
Here is the getinfo.php:
<?php
session_start();
$_SESSION['login']="1";
$x = strval($_GET['x']);
$con = mysql_connect('localhost','root','Newpass123#','seatmapping');
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('seatmapping');
$sql="SELECT name, seatid FROM $x WHERE seatid = 1";
$result = mysql_query($sql) or die("Query Error " . mysql_error());
...
...
?>
I can't get it to work when i click the link it does not display the data from the table.
Please help me. Any kind of help is appreciated. Thanks in advance..
Can you please try this:
Replace the line
echo ''.$seatid.'';
With the below:
echo ''.$seatid.'';
This will solve your problem.
You are not passing the ID of the expected element.
echo ''.$seatid.'';
Replace this line, instead
echo ''.$seatid.'';

Function runs even thou it's not called

I'm looking for a way to clean my DB with a button on a html-page (.php). I have a code that's working OK, but every time I go in to the page the function is cleaning my DB without me pushing the button.
Here is my code
<button id="checkoutbutton" onclick="cleanDb()">Clean DB</button>
<script>
function cleanDb()
{alert("<?php clean();?>")}
</script>
<?php
function clean()
{
$con=mysql_connect("localhost","rss","Habb0") or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db("kalender",$con) or die("Failed to connect to MySQL: " . mysql_error());
$sql='DELETE FROM `bilder` WHERE `stop` < now()';
mysql_query($sql);
echo "Databasen är rensad från gamla bilder";}
?>
Please help me!
PHP is parsed on the server side, JavaScript is parsed on the client side. Any PHP operation will run first, before any javascript (Not considering AJAX).
Use this code, but I am not using javascript. In your case you should consider AJAX. But 2nd option is as follow
<form action="" method="post">
<button id="checkoutbutton" onclick="cleanDb()" name="clebtn">Clean DB</button>
</form>
<?php
if(isset($_POST['clebtn']))
{
function clean()
{
// your code
}
}
?>
you must call ajax for it like this
<button id="checkoutbutton" onclick="cleanDb()">Clean DB</button>
<div id="result_content"></div>
<script>
function cleanDb()
{
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 result = xmlhttp.responseText;
// do your task for result
}
}
var url="clean_db.php";
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
and a PHP File clean_db.php
<?php
clean();
echo "db has been cleaned";
function clean()
{
$con=mysql_connect("localhost","rss","Habb0") or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db("kalender",$con) or die("Failed to connect to MySQL: " . mysql_error());
$sql='DELETE FROM `bilder` WHERE `stop` < now()';
mysql_query($sql);
echo "Databasen är rensad från gamla bilder";}
?>

Progress bar AJAX and PHP

I want to create a progress bar for a server-side task ( written in php )
For learning purposes the example and task would be very simplistic.
I would have a text field on the client page, read a number, pass it to the php script with ajax and make it calculate the sum of all numbers from 0 to number ( simplistic task that would take some time for big numbers, just to simulate some server-side work)
in the .html file I would create a timer that would call a function every n seconds getting the index that my for loop got to and update a progress bar.
My question is :
Is it possible to have in the same php file two functions , and how can I call a specific function with ajax : one that would block looping to number and another one I would call to get the current index the for-loop got to.
The code I have so far :
<!DOCTYPE html>
<html>
<head>
<script>
function myTimer()
{
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("percentageDiv").innerHTML=xmlhttp.response;
alert(xmlhttp.response);
}
}
xmlhttp.open("GET","getter.php",true);
xmlhttp.send();
}
function loop(){
var loop_index = document.getElementById("loop_nr").value;
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("sumDiv").innerHTML="Total sum = " + xmlhttp.response;
clearInterval(myVar);
}
}
xmlhttp.open("GET","server_side.php?nr="+loop_index,true);
xmlhttp.send();
var myVar=setInterval(function(){myTimer()},1000);
}
</script>
</head>
<body>
<div id="percentageDiv"> Percentage div</div>
<div id="sumDiv"></div>
<input type="text" id="loop_nr">
<input type="submit" onclick="loop()">
</body>
</html>
server_side.php
<?php
session_start();
$index=$_GET["nr"];
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $index; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
?>
getter.php
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
Thank You!
Not only one question in here
Your question would be two:
How can I do AJAX calls to specific functions in PHP?
How can I do a progress bar with AJAX?
How can I do AJAX calls to specific functions in PHP?
Your AJAX code is fine. The only thing you have to do in your PHP is receive this call.
Look at your request. You send a variable nr with your request:
server_side.php?nr="+loop_index
That will help us in the php code to determine that this is an AJAX call to do the sum operation. Now in the PHP:
<?php session_start();
//We look at the GET php variable to see if the "nr" is coming
if(isset($_GET['nr'])) {
//Its coming!. Now we procede to call our function to sum
sum($_GET['nr']);
}
function sum($nr) {
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $nr; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
}
Thats it.
How can I do a progress bar with AJAX?
We need to make other AJAX call to request the progress to PHP.
First, we do another AJAX call to retrieve the progress with a timer!
var timer;
//try to delete duplications. Do a generic function that does the request to php
function makeRequest(toPHP, callback) {
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)
{
callback(xmlhttp.response);
}
}
xmlhttp.open("GET",toPHP,true);
xmlhttp.send();
}
function loop() {
var loop_index = document.getElementById("loop_nr").value;
makeRequest("server_side.php?nr="+loop_index, function(response) {
document.getElementById("sumDiv").innerHTML="Total sum = " + response;
clearInterval(timer);
});
timer=setInterval(makeRequest("getter.php", function(response) {
document.getElementById("percentageDiv").innerHTML=response;
}),1000);
}
Then in the php side we retrieve this call as we did before and echo the $_SESSION['progress'] (as you already have)
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
And that's it!
Edit: Sessions must not be saved to a file (default PHP behaviour) because if you do that the "progress" AJAX will be blocked. You should store your sessions in a key-value database such as Redis to achieve parallelism and horizontal scalability.
Here is the solution to made progress bar in PHP without javascript only on server side:
echo "<div style=\"float:left;\">Start... </div>";
for ($i = 0; $i<20; $i++){
echo '<div style="float:left;background-color:red;height:20px;width:'.$i.'px"></div>';
ob_flush();
flush();
usleep(100000);
}
echo "<div style=\"float:left\"> Done!</div>.";
ob_end_flush();exit;

PHP Ajax not working

I have 3 buttons on my page and depending on which one the user is clickingi want to run through ajax call a delete query in my database. When the user clicks on a button the javascript function seems to work but it doesn't run the query in php script.
The html page:
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<script>
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
alert(name); // check if is getting in if statement and confirm the parameter's value
var xmlhttp;
if (str.length==0)
{
document.getElementById("clearMessage").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)
{
document.getElementById("clearMessage").innerHTML= responseText;
}
}
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.send();
}
else
alert('pff');
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="main">
<?php if (session_is_registered("username")){ ?>
<!--Εκκαθάριση παλαιών μηνυμάτων<br />
Εκκαθάριση παλαιών συνεδρίων<br />
Εκκαθάριση push notifications<br />-->
<input type="button" value="Εκκαθάριση παλαιών μηνυμάτων" onclick="myFunction('messages')" />
<input type="button" value="Εκκαθάριση παλαιών συνεδρίων" onclick="myFunction('conferences')" />
<input type="button" value="Εκκαθάριση push notifications" onclick="myFunction('notifications')" />
<div id="clearMessage"></div>
<?php } else echo "Login first."; ?>
</div>
<div id="footer"></div>
</div>
</body>
</html>
and the php script:
<?php
if (isset($_GET["q"]))
$q=$_GET["q"];
$host = "localhost";
$database = "dbname";
$user = "dbuser";
$pass = "dbpass";
$con = mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($database,$con) or die(mysql_error());
if ($q=="messages")
$query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="conferences")
$query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="notifications") {
$query = "DELETE FROM push_friend WHERE time_sent IS NOT NULL";
}
$res = mysql_query($query,$con) or die(mysql_error());
if ($res)
echo "success";
else
echo "failed";
mysql_close($con);
?>
You have a few issues.... and this got the text from clearDatabase.php... I just had it output some generic text
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<script>
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
// Issue #1: str is not defined anywhere
var str = "sfs";
alert("name " + name); // check if is getting in if statement and confirm the parameter's value
var xmlhttp;
if (str.length==0)
{
document.getElementById("clearMessage").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)
{
// Issue #2: responseText was not defined... it needs to belong to something
document.getElementById("clearMessage").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.send();
}
else
alert('pff');
}
</script>
note: anyone who runs "clearDatabase.php?q="+name can delete whatever from your database. Also, make those changes but it still may not work if the code on "clearDatabase.php?q="+name doesn't work.
Also: it would have been a lot easier for us to troubleshoot this for you if you had provided the console errors.
How I solved this: I just copied and pasted this in a document myself and opened up the Chrome version of Firebug (control+shift+j) and there was red text to tell me str wasn't defined. So I defined it as var str="". Then I realized it was hitting if (str.length==0) so I give it a value. Then, I got a new error that the responseText wasn't defined. I googled how to use the response form a javascript ajax call (I only know jquery) and looked at the examples. I saw it needed to be from the request and added xmlhttp.responseText;. Then it worked.
Try;
xmlhttp.open("POST","clearDatabase.php?q="+name,true);
instead of;
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
first open the xmlhttp request.
try this:
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("clearMessage").innerHTML= responseText;
}
}
xmlhttp.send(null);
why dont you use jquery -> ajax() ?
And your code will look like this:
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
alert(name); // check if is getting in if statement and confirm the parameter's value
$.ajax({
type: "GET",
url: "clearDatabase.php?q="+name,true,
success: function (res){
$("#clearMessage").html(res );
}
});
}
else{
alert('pff');
}
}

PHP & AJAX & MySQL integration

I'm trying to get the code below working so that it will call a JS function to pass a value to my PHP file which will return a number of values from a MySQL database. This is part of an assignment I thought would be quite straightforward but I think my problem is with the JavaScript event handler - how to reference the input value maybe?
The HTML:
<form>
<input type="text" name="users" onkeydown="showUser(this)"/>
</form>
<div id="txtHint">
<p id="responder"><b>Person info will be listed here.</b></p>
</div>
The showUser() function:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("responder").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)
{
document.getElementById("responder").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/student_query.php?q="+str,true);
xmlhttp.send();
}
</script>
The PHP:
<?php
$q=$_GET["q"];
// Step 1
$conn = mysql_connect("localhost", "root");
// Step 2
mysql_select_db("collegeData", $conn);
//Step 3
$sql="SELECT * FROM studenttable WHERE studentID = '".$q."'";
$result = mysql_query($sql);
// Step 4
while ($row = mysql_fetch_array($result))
{
// Step 5
echo "Hello $row[firstName] $row[lastName]<br/>";
echo "Your two course modules are $row[moduleNo1] and $row[moduleNo2]<br/>";
echo "<tr><td> $row[firstName]</td><td> $row[lastName] </td> <td> $row[studentID] </td> </tr>";
echo "<br/>";
}
// Step 6
mysql_close($conn);
?>
Like I said, i think my problem is in the event handler, I'm not great with JS. I'd appreciate any help.
Looks like you're sending the input element to your function, not it's value. Try
<input type="text" name="users" onkeydown="showUser(this.value);" />
Also, you should protect your database query from protection by changing your PHP to
$q = mysql_real_escape_string(trim($_GET["q"]));
if($q == "")
{
echo "";
exit;
}

Categories