<img id="image" src="jj.png" onclick="randomizeImage();"/>
<h2 id="Score" name="Score1">0</h2>
<script>
var counter=0;
function randomizeImage() {
counter++;
var test= document.getElementById('Score');
test.innerHTML= counter;
}
</script>
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$user_Name = $_COOKIE["username"]; //i stored the username as a cookie and retrieved it here
echo $user_Name; //echo it so i can check if it is right
$New= $_POST["Score"]; //**this is the part which is undefined**
$sql = "UPDATE User SET Score = '$New' WHERE ID='$user_Name'";
if (!mysql_query($sql,$con))
{
die('Error please try again ' . mysql_error());
}
mysql_close($con)
?>
I have an image that whenever i click on it, it will call a function which will increase a counter by 1. This score will be reflected on the html side and increase whenever i click on the image. However now i want to bring this counter data into php where i can upload it onto a database where it matches the user's username which he/she entered in a previous phpfile. I cant bring the value of score over? It keeps saying undefined index.
I have two colums called ID and Score. ID is where i score the user's username and Score is the score from the counter. I want the Score to updated everytime the image is pressed with respect to the username.
Database name is :database
Table name is: User
Is there anyway to do this without AJAX?
You need to hook an ajax request to the randomizeImage() function. With the AJAX request, you can make a post request to the PHP page which you have created so it would save the score.
See AJAX
function randomizeImage() {
counter++;
var test= document.getElementById('Score');
test.innerHTML= counter;
$.post("yourphpfile.php", {score: counter}, function(result) {
//should be saved
}
}
This is the JS side. PHP side - you have to check if there is a POST request with the variable score.
<?php
if (isset($_POST['score'])) {
$score = intval($_POST['score']);
//check if user already has score.
$scoreQuery = "SELECT score FROM tbl WHERE username = '$username'";
//run the query, if user has score:
$query = "";
if (user has score already) {
$query = "UPDATE tbl SET score = score + $score WHERE username = '$username'";
} else {
$query = "INSERT INTO tbl (score, username) VALUES ($score, '$username');
}
//run the query
}
This is how you can send an ajax request to the server. Make sure to include jquery first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var counter=0;
function randomizeImage() {
counter++;
var test= document.getElementById('Score');
test.innerHTML= counter;
$.ajax
(
"ajax.php",
{
method: "POST",
data: { score: counter}
}
);
}
</script>
Next you have to put your PHP code into a separate file, I call it "ajax.php".
<?php
$score = filter_input(INPUT_POST, "score");
if (isset($score) && $score != "") {
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$user_Name = $_COOKIE["username"]; //i stored the username as a cookie and retrieved it here
echo $user_Name; //echo it so i can check if it is right
$sql = "UPDATE User SET Score = '$score' WHERE ID='$user_Name'";
$result =mysql_query($sql) or die("could not update" . mysql_error);
if (!mysql_query($sql,$con))
{
die('Error please try again ' . mysql_error());
}
mysql_close($con)
}
?>
Related
I have an HTML form starting with an input field, where the user have the option to write a promo code to get some discount ....
What I am trying to do here. I need to create a keyup functionto check if the typed code is found in the MySql Promo Codes table.
If found, write something in the placeholder ...., else, write something else ....
Also if the form is submitted in need the PHP to write 'Yes' in the code corresponding MySql Used column...
<form id="form" class="form" name="RevitForm" action="form_revit_architecture_submitted" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
<div class="field" style="background-color:#f3f3f3;">
<span id="promo-msg" style="color:#093; position:relative; bottom:3px; font-style:italic; font-size:13px">[HTML is replaced when successful.]</span>
<center><input style="font-family:Lato; text-align:center; max-width:200px;" type="text" id="PromoCode" name="PromoCode" maxlength="5" size="15px" placeholder="Promo Code"></center>
</div>
//other input fields
</form>
<!-- Promotion Code Match -->
<script>
$("#PromoCode").keyup(function() {
if ($(this).val().length == 5) {
//post the code and check the it in the MySql table thru the PHP file "request.php"
//if code found {write something in $(#promo-msg) } else {do something else}
}
});
</script>
And in the PHP in need to excute something like
<?PHP
$code = ucwords($_POST['PromoCode']);
$con=mysqli_connect("localhost","x","y","academy_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
// if $code is found and the corresponding `Used` column does not == 'Yes' return as found
//else return as not found
?>
To do that, we need 2 files.
HTML, form + jQuery AJAX keyup event and check DB
PHP connect to DB to check the promo code
1.HTML
<html>
<head>
<title>Promo check</title>
<!-- load jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 10;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' is already used correct.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<input type='text' id='code'>
<div id='Promo_code_status'></div>
</body>
</html>
2.PHP: check_code.php
You will need to use your connection data ($host, $user, $pass, $dbdb) and maybe change the table & field names.
<?php
//connect to database
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select promoCode, used from testtable where promoCode = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
Do it like this:
"SELECT * FROM Promo Codes WHERE Code LIKE '$code' AND Used='yes' "
Also,To update parameter 'used':
UPDATE Promo Codes SET used='Yes' WHERE Code= '$code'
For the keyup function, you need to learn about AJAX requests. Since it's the medium for communicating with the server through the client
jQuery AJAX: http://api.jquery.com/jquery.ajax/
I am using jquery to feed variables to a php page.
I want the php to clear a table in the database, load new data based on the variables, query the new data and echo out results.
The problem is, the php doesn't seem to be clearing the table each time I hit the php page. When I feed two sets of variables to the php page, the same results appear for both queries. The results are a combination of what I want. What am I doing wrong, anyone know?
jquery:
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : strYear, race: 'USP', type: strType},
success: function(data) {
var objPrez = jQuery.parseJSON(data);
fillTotal(objPrez, tbl_prezresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
//get gov totals
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : 2010, race: 'GOV', type: strType},
success: function(data) {
var objGov = jQuery.parseJSON(data);
fillTotal(objGov, tbl_govresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
getTotals.php:
require_once ('constants_test.php');
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
if( $_POST) {
$type = mysqli_real_escape_string($db, $_POST['type']);
$year = mysqli_real_escape_string($db, $_POST['year']);
$race = mysqli_real_escape_string($db, $_POST['race']);
$db->query("delete from elections_temp");
$data = array();
$q = "INSERT INTO elections_temp (SELECT * FROM elections where electionOffice = '" . $race . "' AND electionYear = '" . $year . "' AND electionType = '" . $type . "')";
$db->query($q);
$q_sums = "select firstName, lastName, party, sum(votes) as totvotes from elections_temp group by lastName order by totvotes desc";
$result = $db->query($q_sums);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//Add this row to the reply
$data[] = $row;
}
echo json_encode($data);
$db->close();
} else {
echo "You shouldn't be here.";
}
What you are doing is the following:
2 ajax calls that call the php script at the same time (probably a delay of a few ms between them).
The server then does what you want it to do, but strange things happen because of your temp table that is created/truncated every request.
What happens is the following:
request1 enters
runs the php code
request2 enters
runs request2 code
request1run locks tem table in database and starts creating it and stuff
request2run wants to create the same temp tabel but can't because request1run is still doing stuff
request1run ends doing his stuff in the db temp table
request2run now does his thing with the temp table, delete all records and add stuff
request1run has to wait before he can select stuff from the temp table because request2run is still doing his business.
request2run finished creating the temp table and request1run can slect his data and return it to the client
request2run select data and returns it to the client
So, because you fire both ajax call at the same timen they end up messing with each other on the server.
Your server is probably not fast enough to handle request1 before request2 kicks in.
I think you do not need the extra table. You can all do it in one sql
$query = 'select firstName, lastName, party, sum(votes) as totvotes from elections
where electionOffice = "' . $race . '" AND electionYear = ' . $year . ' AND electionType = "' . $type . '"
group by lastName, firstName, party order by totvotes desc';
If performance is a problem, add an index to electionOffice, electionYear and electionType (all in one index).
* Resolved *
I implemented SimpleCart(js) to my one project.
One can register and login.
Once logged in you can use the cart to purchase items.
I have one problem, because simplecart(js) saves the cart to localstorage, if you login with a other account. You see the same cart results.
Does anyone have a php sql solution for this, to store the cart results into sql for each individual session user?
I resolved this issue with this,
It's a basic technique, but it works perfectly for what I need, I'll still tweak the php to check if the cart item exists in the db, whether to update or create.
jQuery
$(".saveCart").click(function(){
$(".itemRow").each(function(){
var custId = "<?php echo $_SESSION['Username'] ?>";
var itemName = $(this).find(".item-name").text();
var itemPrice = $(this).find(".item-price").text();
var itemQty = $(this).find(".item-quantity").text();
var itemTotal = $(this).find(".item-total").text();
$.ajax({
// Enter below the full path to your "cart" php file
url: "cart.php",
type: "POST",
data: {custId: custId, itemName: itemName, itemPrice: itemPrice, itemQty: itemQty, itemTotal: itemTotal},
cache: false,
success: function (html) {
// If form submission is successful
if ( html == 1 ) {
}
// Double check if maths question is correct
else {
}
}
});
});
});
PHP
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="INSERT INTO cart (Id, itemName, itemPrice, itemQty, itemTotal)
VALUES
('$_POST[custId]','$_POST[itemName]','$_POST[itemPrice]','$_POST[itemQty]','$_POST[itemTotal]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
if ($sql) { echo "1"; }
else {echo "2"; }
mysql_close($con);
?>
mysql_query("UPDATE table SET sessid = ".session_id()." WHERE user = ".$user_id);
Something like that?
This is what I want, on a PHP page called input.php the user submits a username by a html form. This gets stored into the MYSQL database. There is a page called results.php which querys the MYSQL database for all usernames.
What I need to happen is that every 5 or so seconds some jquery code (maybe getJSON) will get a JSON string from results.php (the same page). This JSON string may be updated as a user may of added more usernames on the input.php page.
This is the input.php file
<form name="input" action="<?php $_SERVER['PHP_SELF']?>" method="post">
Usernames: <input type="text" name="usernames" />
<input type="submit" value="Submit" name="submit" />
</form>
<?php
if(isset($_POST['submit'])) {
$link = mysql_connect('', '', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('', $link);
if (!$db_selected) {
die ('Can\'t use : ' . mysql_error());
}
$result = mysql_query("INSERT INTO users(user_name) VALUES('".$_POST['usernames']."')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
?>
This is the results.php file
<script
type="text/javascript" src="jquery-1.7.1.min.js"></script>
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query("SELECT user_name FROM users");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$names = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $val) {
$names[][$key] = $val;
}
}
echo json_encode($names);
?>
<script type="text/javascript">
$.getJSON("http://localhost/test/results.php", function(json){
alert("JSON Data: " + json);
});
</script>
<div></div>
I am stuck on what jquery to put or even if i'm doing this properly. The end result is like Gmail where you receive email without a page refresh. But my system would retrieve usernames from the database every 5 seconds without a page refresh. I have read about getJSON method and I am totally out of my depth with it so I may need some very in depth explanation. If im going about this objective the wrong way please let me know and inform me of good practises in how to go about this.
I try this url in my browser with no result apart from the echoed JSON string from the php code.
this is my JSON string
[{"user_name":"matt"},{"user_name":"matt"},{"user_name":"peter"},{"user_name":"jim"},{"user_name":"sam"}]
what you are looking for is called AJAX, you will need javascript in order to acomplish it. if you want a sleek and easy way I would recommend jQuery.Your code would look something like this:
setTimeout(function(){
$.post("results.php",function(result){
//Do somthing with the result Array or object
},"json");
},5000);
moreover since you only are taking 1 piece of data "usernames" you should return an array json not an object json
["matt","matt","peter","jim","sam"]
it should take less bandwith for both, you and your user.
NOTE: you should remove the jquery script from results.php, the only thing you should retun is the json itself. if any doubt just ask
If you want to use results.php to do both things (i.e. display the usernames as well as respond to the JSON query) then you will need to split the file into two branches. Use a _GET variable to specify which branch. So for example, you would run .getJSON on results.php?json=true instead of just results.php. Now inside results.php have an if branch that checks for the existence of this _GET variable, and if so, grab the data you need, echo it in a json-encoded string, and then exit(). Do all this before anything else in results.php, even before the <script> tag .
Edited to provide code: (edited from OP's question)
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query("SELECT user_name FROM users");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$names = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $val) {
$names[][$key] = $val;
}
}
if (isset($_GET['json'])) {
echo json_encode($names);
exit();
}
?>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$.getJSON("http://localhost/test/results.php?json=true", function(json){
alert("JSON Data: " + json);
});
</script>
<div></div>
you can use setTimeout.
setTimeout( function() {
getData()
}, 5000);
function getData() {
$.getJSON("http://localhost/test/results.php", function(json){
alert("JSON Data: " + json);
});
});
}
I have a page that is pulling data through jQuery but it is only pulling the return code. Here is my code:
<script type='text/javascript' language='javascript'>
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val()
},
function (response) {
$('#contact').val(response).show();
$('#email').val(response).show();
$('#phone').val(response).show();
})
}
</script>
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . $_POST['id'] . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
if (mysql_num_rows($query) > 0) {
while ($get = mysql_fetch_array($query)) {
$priContact = $get['priContact'];
echo $priContact;
echo $get['priEmail'] . " | " . $get['priPhone'];
}
} else {
echo "No users";
}
So the call is pulling from getCU.php whenever the onchange event handler is called. That is why this is in a function. What I want to do is every time a user chooses something from the option list the text values change according to what was selected. I have the php page pulling from a db and echoing out the code correctly. jQuery id pulling the data from the php page correctly, but I cannot get the code to place the single details in each of the text boxes.
So what I want to happen is this:
A user selects a name from a drop-down box. Then the mysql data attached to that name would be displayed on the page in form text fields.
Let me know if more information or code is needed.
I think you'll be better off structuring your data. My general recommendation is JSON.
// QUICK WARNING: Don't take unparse GET/POST responses.
// This is asking for trouble from SQL injection.
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . mysql_escape_string($_POST['id']) . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
$retVal = array();
if (mysql_num_rows($query) > 0) {
$retVal['data'] = array();
while ($get = mysql_fetch_array($query))
{
$retVal['data'][] = $get;
}
} else {
$retVal['error'] = 'No users';
}
header('Content-type: application/json');
echo json_encode($retVal);
Javascript:
<script type="text/javascript">
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val(),
dataType:'json'
},
function (response) {
if (response.error) {
//handle error
}
else
{
$('#contact').val(response.data.priContact).show();
$('#email').val(response.data.priEmail).show();
$('#phone').val(response.data.priPhone).show();
}
})
}
</script>