How to pass Javascript variables to PHP [duplicate] - php

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).

Related

Update database only by pressing link

I have this code with some images, like this:
<img src="../images/woods/oak.png" onclick="loadXMLDoc(this), add_items_oak(this), add_skills_oak(this)" class="a" name="oak"/>
<img src="../images/woods/oak.png" onclick="loadXMLDoc(this), add_items_oak(this), add_skills_oak(this)" class="b" name="oak" />
When one of them is pressed, an ajax call is run:
function loadXMLDoc(h)
{
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)
{
var getEle = document.getElementsByClassName('woods1')[0];
var imagePath ="../images/woods/oak_cut.png";
h.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","../database/update.php",true);
xmlhttp.send();
}
Which then updates the database by the use of this file:
<?php
require('../includes/db_connect.php');
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('
UPDATE items_woods t1 JOIN skills_woodcutting t2
ON t1.id = t2.id
SET t1.oak = oak+1,
t2.exp = exp+13
WHERE t1.id = ?;
')) {
/* Bind parametres */
$stmt->bind_param('i', $id);
/* Insert the parameter values */
$id = 1;
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terrible wrong' . $mysqli->error;
}
?>
The problem now is that people can use the url to simulate a click on one of the images. Like writing something like: www.examplepage.com/database/update.php
I need update.php to check wether or not a image is clicked on.
I tried some code by having a value in the <img> tag that was set to true, and only if that was true at update.php, it would execute the code. This didn't help and since I am trying to find a solution that can't be cheated with, I thought about asking here. Any suggestions or advice? Thanks in advance.
What you want is not possible through any sort of standard method. There is no way to require someone to click a link vs visiting a URL directly.
You will have to do something like generating a one-time hash that only works for a short period of time, and only allow the script to work if that was passed in the link.
So if a user clicks a link with that hash, it'll work once, but future clicks with that same hash won't. They'd have to find the image again and click it a second time with a new hash to trigger the same function.
edit:
If you're doing what it looks like and making a sort of browser game where users see resources and click to claim them, could you generate a map first, and send the x/y coords they're clicking on, and then track that the resource was deleted?
Then if they try to "cut" the same x/y coord again, it wouldn't work since they already harvested it.
You can test for the POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// … your database code
}
This would at least stop the update happening if the user simply visited the URL because that would constitute a GET request

pass the value of the query too PHP from java script

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.

Remove credit on pressing a button PHP MySQL AJAX

I'm trying to make a simple credit page where people have that much credit, and by clicking on a button next to their name it will remove on credit
<table border="1">
<tr>
<td>Name</td><td>Massages left</td>
</tr>
<?php
mysql_connect("localhost","dbuser","password");
mysql_select_db("db");
$command = "select pass_name, credit_left from pass;";
$result = mysql_query($command);
//If there is, list that particular entry
while ($data = mysql_fetch_object($result))
{
print "<tr><td>" . $data->pass_name . "</td>" .
"<td>" . $data->credit_left . "</td></tr>\n"
// Button here that you click and make credit go down one;
}
?>
</table>
For example it will say Ben - 2credits - click here to remove one.
Thanks
EDIT
okay here is what I have:
the script is
<script>
function removeOneCredit(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("credit").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","removeonecredit.php"+str,true);
xmlhttp.send();
}
</script>
the form is:
while ($data = mysql_fetch_object($result)) {
print "<TR><TD>".$data->pass_name."</TD><TD id='credit'>".$data->credit_left."</TD><TD><form><input type='submit' value='- 1' onsubmit='removeOneCredit(?pass_id=".$data->pass_id."&credit_left=".$data->credit_left.")'></form></TD></TR>\n";
}
the removeonecredit.php is
<html>
<?php
$pass_id = $_GET[pass_id];
$credit_left = $_GET[credit_left]-1;
//change value
mysql_connect("localhost","user","pw");
mysql_select_db("db");
$command = "update pass set credit_left='$credit_left' where pass_id='$pass_id';";
mysql_query($command);
//now print value
mysql_connect("localhost","user","pw");
mysql_select_db("db");
$command = "select credit_left from pass where pass_id='$pass_id';";
$result = mysql_query($command);
$data = mysql_fetch_object($result);
echo $data->credit_left;
?>
</html>
If I pass the string manually at the end of removeonecredit.php, it works, so it must be the Ajax part of things...
Use a from with a button and use an AJAX script in JavaScript to update the database without reloading the page. If you don't care that the page reloads, then you can just use the form but you don't have to write the AJAX script. To update the database for a single user, you can iterate through your database, and find the user you are looking for by a unique identifier such as an id, or a username:
For example, using the UPDATE MySQL command:
UPDATE table_name
SET credits_left='1'
WHERE username='Bob'
So this will update the credits value only for the person with username 'Bob'.
I know this isn't very specific, but if you make your question more specific, I might be able to help you better.
turns out the = in the function arguments is a problem, I posted a question on how to escape it here: Javascript escape a equal sign PHP
If you want to make that change using PHP, you would have to make a form and submit to the same page. PHP renders code on the server and sends HTML to the client (the user on the computer). If you want it to be reflected in the database, you would have to run a mysql query to update that field. Then once the form is submitted, the top of the page can process it, and the new output would be loaded.
Another option would be to use javascript. In this case it would not be necessary to reload the page.
<script>
var count = 2;
$(document).on('click', '#clickButton', function(){
$('#countDiv').text(count--);
});
</script>
And your html/php page would have to have a button with id="clickButton" and a div like <div id="countDiv"></div>
I didn't test this out. But I hope it helps or takes you in the right direction!

Getting Started with AJAX - Updating Form via PHP

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.

Code does not stop from submitting the form even when user enters the same email again and again

I am trying to send a AJAX request to the server when a user submits a form, I am doing this to check out if that email is already in use by someone else or if it is new.
This is my javascript AJAX function
function check_entireform()
{
var new_email = document.getElementById('jemail').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)
{
var y =xmlhttp.responseText;
if(y=="user with that email is already registered")
return false;
  }
}
var x ="user_exists.php?email="+ new_email;
xmlhttp.open("GET",x,true);
xmlhttp.send();
}
This is my html input tag
<form method="post" action="./new.php" onsubmit="return check_entireform()">
<input type="text" name="email" id="jemail"/>
</form>
This is my user_exists.php file
<?php
$email=$_GET["email"];
if(mysql_query("SELECT email FROM user_info WHERE email='$email'"))
echo "user with that email is already registered";
else
echo"user got a new email";
?>
When the user submits the form, I would like to send the user email to the user_exists.php file through the AJAX and then check out if that email is already in use by someone and echo back some information if it already in use.
I don't know where it's going wrong. I have been submiting same email but it does not echo and does not stop me from submitting the form.
If there are any better solutions to find out if email is already in use by someone would be great.Thanks
The first A in AJAX is for Asynchronous.
It means that the callback function (the one you defined for onreadystatechange) will only run when the server responds. On the other hand, your submit handler check_entireform will return much earlier than that. It returns undefined, which evaluates to false, so your form is not submitted.
Whatever you want to do, you should do in the callback function.
Always prevent submission and pass reference to form:
<form method="post" action="./new.php" onsubmit="check_entireform(this); return false;">
Accept the reference:
function check_entireform(theform) {
Then submit the form if needed:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var y =xmlhttp.responseText;
if(y != "user with that email is already registered")
theform.submit();
}
jsFiddle Demo - without AJAX, only simulation
Return something more logical from your PHP
Tip: Instead of returning a long string from PHP, you should simply return 0 or 1. You should think of the AJAX query like a Yes-No question in this case (Can this email be used?). 1 will mean Yes while 0 will mean No.
So you could change your code to:
var canBeUsed =xmlhttp.responseText;
if (canBeUsed) theform.submit();
It will become much easier to read and maintain.
URL-encode query string parameter values
In this line:
var x ="user_exists.php?email="+ new_email;
You should URL encode the new_email variable, because certain characters (like &) have a special meaning in the query string and shall be encoded. You can use the encodeURIComponent() function to do this:
var x ="user_exists.php?email="+ encodeURIComponent(new_email);
Sanitize input in your PHP
ALWAYS sanitize (and validate) any data that comes from the outside. In its current form, your code is vulnerable to SQL Injection, which is a HUGE problem.
Before inserting data into your query, you should use mysql_real_escape_string() on it (or even better, use PDO for your database stuff).
$email = mysql_real_escape_string($_GET["email"]);
if(mysql_query("SELECT email FROM user_info WHERE email='$email'"))

Categories