Remove credit on pressing a button PHP MySQL AJAX - php

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!

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.

MySQL Query Within JavaScript

I am working on a form whereby JavaScript is used to add another line item. The purpose is to add line items to an invoice. I have successfully got this to work ok when using text boxes in my form, but am stuck on how to get this to work with a dropdown box that makes a call to mysql to get the dropdown box data.
Here is what I have.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
?>
<script type="text/javascript">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><select name='myInputs[]'><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>";
document.getElementById(divName).appendChild(newdiv);
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><select name="myInputs[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>
So here is some info on what is going on. Right now, the JavaScript code above shows the MySQL query in it. This kills the add line item functionality. If I simply remove the query but leave the other php in, the add line item begins to work again, but of course there is no data in the drop down.
In the form itself, it gets the first line item from the database without using javascript and this is working ok.
I feel like I am getting close, but don't know where to go from here.
Thanks in advance.
EDIT:
Thanks to Nick, I got this working. Here is the code.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
?>
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (++counter) + " <br><select name='myInputs[]'>" + xmlhttp.responseText + "</select>";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "update_text.php", false);
xmlhttp.send();
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><select name="myInputs[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>
</div>
<input type="button" value="Add" onClick="addInput('dynamicInput');">
</form>
Then the update_text.php
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
And here is my php post into the database which is not working for the javascript add line item, only for the original entry that is created from the form. (I have other fields besides the dropdown).
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$company = mysql_real_escape_string($_POST['company']);
foreach($_POST['item'] as $i => $item)
{
$item = mysql_real_escape_string($item);
$quantity = mysql_real_escape_string($_POST['quantity'][$i]);
mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error());
}
echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
Thanks, please let me know if I can clean this up better.
Sadly the way you'r trying to do it wont work due to the nature of PHP.
When a client requests your page from the server ALL the php is executed.
So the php block inside your javascript function is actually just the static result of your php.
You'll need to use XMLHttpRequests/Ajax to request the new data from the server.
Here's a quick (and probably fairly bad) example!
Modification to your javascript function:
var counter = 1;
function addInput(div) {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var d = document.getElementById(div);
d.innerHTML=d.innerHTML +"<div>Entry " + (++counter) + " <br><select name='myInputs[]'>" + xmlhttp.responseText + "</select></div>";
}
}
xmlhttp.open("GET", "updated_list.php", false);
xmlhttp.send();
}
A new php file on your server: (updated_list.php)
<?php
// you'll need to include stuff to connect to your database here
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
update
I did say it was a bad example :) my original code overwrote the contents of your div instead of adding to it, which ive updated. this was only an example, you should read up on AJAX and how to request data from the server.
You cannot use server code inside a javascript function after the page is load.
The server side code is like it's name - code that runs on the server. so after the page finish loading it "get back" to the client and only client code (javascript) can run now.
so your line
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><select name='myInputs[]'><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>";
is a bit mistake.
what you can do is to return the data from the database to the javascript (using json will be the best option) and then build the select box dynamically using the raw data that came from the server that is now a javascript data.
so let's say your data is
var data = [{name:'n1'},{name:'n2'},{name:'n3'}];
You can run this data using javascript and build your combo:
var newSelect = document.createElement('select');
for(var i=0;i<data.length;i++){
var name = data[i].name;
newSelect.options[newSelect.options.length] = new Option(name,name);
}
This is a classic example for AJAX (Asynchronous Javascript And XML) - the basic concept is that when an action is carried out (e.g. a button clicked to show content), some JavaScript calls a PHP (asynchronously), the PHP runs, returns an XML file (although this can actually be any file format you want, some people now prefer to use JSON because it's easier to parse), and the contents of the this XML / JSON are displayed, also using JavaScript.
Although the example above is displaying content, there's no reason why any action where you need to run on the server (e.g. inserting data to a database) can't also be done asynchronously.
SO is not a place for code to be written for people - so now I've given you a hint as to where to start, and as an exercise for the reader ( / question asker!), have a look at some AJAX tutorials, make sure you understand the concept, write some code, and come back if still can't get it working!
Good luck :)

How to pass Javascript variables to PHP [duplicate]

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

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.

Categories