MYSQL subtract value if input differs - php

I have a text area (txt_desCription) on a form that is used to calculate a score. The score is weighted as follows:
If the input in the text area is smaller than 75 words, 5 points is added to a the col_score column(TINYINT(1) in the tbl_score table of the database.
If the input in the text area is greater than 75 words, 10 points is added to a the col_score(TINYINT(1) column in the tbl_score table of the database.
An onblur event calls the jquery script that 'counts' the words and then sends it to the add_score.php page that handles the update event. Code below:
if (isset($_POST["txt_desCription"])); {
$sessionscore = $_POST["txt_desCription"]; // ◄■■ PARAMETER FROM AJAX.
if ($sessionscore <= 75) {
$descscore = 5;
} else if ($sessionscore >= 75) {
$descscore = 10;
}
$updatesql=sprintf("UPDATE tmp_score
SET col_score=col_score+%s
WHERE sessionid = %s",
GetSQLValueString($descscore, "int"),
GetSQLValueString($_SESSION['sessionid'], "text")
);
$result=mysql_query($updatesql) or die(mysql_error());
}
It works perfectly well, but what I cannot figure out is how to update the score if the user goes back and make changes to the text in the text area?
With other Words, what if the user changes their mind about the answer and goes back and change their answer to a shorter or longer one? Meaning the value will change from 5 to 10 or vise versa.
Please help. My hair is thinning by the second :-)

I think you need to use onchange jquery event and send ajax request every time user change the value. You ajax request will look something like this
jQuery(document).ready(function($){
$(document).on("change","#textareaId",function(){
$.ajax({type: "POST",
url: 'yourUrl', //Ajax request url here
data:{}, // data to update here
success: function(data) {
//do something with response here
}
});
});
});
I hope this will help you out.

Related

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

PHP/JQuery: Posting to a PHP Script then returning the values and updating HTML with JQuery

I'm fairly new to PHP and really new to JQuery.
So I writ some JQuery that does some calculations, I writ something below that is similar:
//on change of a selectbox with the class item
$('.item').change(function() {
// set variable id as the id name of this id
var id = this.id;
// price variable is equal to the value of the element id 'hiddenprice'
price = $("#hiddenprice").val();
// number of items is the value of the select box
numberofitems = $(this).val();
// number of days is equal to a php variable I set on the page
numofdays = "<?php echo $length->days; ?>";
//totalprice is equal to the 'price' multiplied by 'numofdays'
totalprice = Number(price) * Number(numofdays);
//calculates final total by multiplying the 'totalprice' by 'numofitems'
finaltotal = Number(totalprice ) * Number(numofitems);
//updates the HTML with the new price
$('#'+id).html("€" + finaltotal.toFixed(2));
});
I was trying this and although I got it to work, after reading up some I am aware that because this script is in my footer of the page that is getting updated, it is unsafe and easy to manipulate if a user wanted to be malicious.
So I want to do the calculations server side, by posting values to a PHP script and then returning the values.
// POST values to PHP Script
$id = (posted select id);
$price = (#hiddenprice variable value);
$numofitems = (posted value of the select);
$numofdays = $length->days;
$totalprice = (int)$price * (int)$numofdays;
$finaltotal = (int)$totalprice * (int)numofitems;
//Then push $finaltotal and $id back to the user viewed page
$('#'+<?php echo $id; ?>).html("€" + <?php echo $finaltotal; ?>.toFixed(2));
I'm just not sure how to push them to the page without refresh and then return them, also without refresh.
Again, sorry if this is simple, I have looked at JQuery form plugins, I just wondered if there is more apt solution for what I would like to do.
Thanks in advance.
You may want to check out ajax, it can post or get data without refreshing the page. Also the answer of this question may be helpful too.
You need to use AJAX. This sends data to the server and allows you to execute a callback once you receive a response.
If you are using jQuery, then read up about the $.ajax method.
To handle the response, the easiest data type to use is JSON.
So a quick example
Javascript
$.ajax({
url: calculation_url.php,
method: 'post',
dataType: 'JSON',
data: {price: price, days: numofdays },
success: function(response) {
// you should check a valid response was received
$("#result").html(response.html);
}
});
PHP - calculatin_url.php
$price = $_POST['price'];
$days = $_POST['days'];
// do calculations
// send data back as json
die(json_encode(array('html' => $finalTotal)));
To start this process you will need to attach events to the calculation button. Read about registering events with the on method and you may find it helpful to read about the event.preventDefault() method.

Refresh div, but only if there is new content from php file

Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds

Count clicks on one button, save it to MYSQL and then display the current value (AJAX, PHP)

Here is what I want to accomplish on http://geheimprojekt.nomachines.org/
User clicks on "Nochmal!" Button (New word combination is generated)
Send the click to my MySQL database (withou reloading the page), increase "clicked" row by 1
Update the text in a paragraph "n Word combinations have been generated so far."
This is my first attempt to work with AJAX.
I have jQuery knowledge but i can't connect the dots it seems.
The SQL
CREATE TABLE IF NOT EXISTS `sggcount` (
`counter` bigint(20) NOT NULL DEFAULT '2'
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german2_ci;
--
-- Dumping data for table `sggcount`
--
INSERT INTO `sggcount` (`counter`) VALUES
(2);
To get this to work is very simple. You need some html for the future div where you want to place the couting:
<div id="counting"></counting>
Then right at the end of the generator() function you add this:
function generator(){
/*your code here...*/
var element = document.createElement("div");
element.setAttribute("id", "result");
element.appendChild(document.createTextNode(name));
document.getElementById("placeholder").appendChild(element);
/*the ajax code here*/
var url='urltophpfile/phpfile.php';
$.get(url,function(data){
$('#counting').html(data+' Word combinations have been generated so far.');
});
}
Now in your phpfile.php file you will need the code to increment the count. I guess you know how to do this part if now i can help with it too. I'll add some sample code here so you have an idea.
<?php
mysql_connect('localhost', 'db-sgg', 'password') or die('Cannot connect to database server');
mysql_select_db('db1152127-sgg') or die('Cannot select database');
$databasecall = mysql_query("SELECT counter FROM sggcount WHERE counter > 1");
/*so here you select the already stored value and then you make an update to increment it*/
mysql_query("UPDATE sggcount SET counter=counter+1");
$count = mysql_fetch_assoc($databasecall);
echo $count['counter']+1;
?>
By doing the echo above you will return the incremented value and the ajax will display it.
Update 1
Added more comprehensive php code
NOTE: if you add the jquery script please change the generator function to use jquery.
Using jQuery you could bind click event to your button and make ajax request.
JQuery ajax doc
On server side your PHP page should update SQL data.
Follow Javascript demo code
$(document).ready(function(){
$('button-selector').click(function(){
//use jquery ajax call to call php server page that update SQL data
$.ajax({
url: "updateClick.php",
context: document.body
}).success(function() {
//success callback
});
});
});
to send AJAX request on clicking use:
$('#button').click(function(){ // when user `click` element with `id="button"` (#button)
$.ajax({ // Start AJAX call
url: 'accept.php', // URL to send AJAX request
success: function(data) { // Function to execute on SUCCESS reply (reply data as paramenter)
var cc = $('#clicks_count').html(); // In your element with `id="clicks_count"` you store your click count (`<a id="clicks_count">21</a>`). Assign to `cc` javascript variable value of clicls_count
$('#clicks_count').html(cc + 1); // Increasing clicls_count on 1 and write it to `<a id="clicks_count">22</a>`
}
});
});
At accept.php use script increasing clicks counter by 1.

ajax form like structure

I will make this as short and descriptive as possible (considering my case is way longer).
Lets say I have 2 database tables with the following structures:
User table:
id ---- username---- gold
Items table:
id----- item_name---- item_price
What I am trying to achieve is brainstorming, I tried this with over 20 script combinations. I need to be able to echo out all items in the table to a good layout (done)
Have a text box for the user to type in the value required to be bought.
an a href to submit the amount, deduct the price of the item from the amount of gold the user has, then add 1 to the inventory. I am not requiring php code, as it is easy. All I need is help with trying to update the value typed in "Live". The layout of the "shop" will look something like this:
while($_row = mysql_fetch_assoc($query)){
echo out name...
<input type = 'text' name = 'to_buy_value'/>
<a href = 'javascript:;' class = 'buy'>Buy</a>
}
I hope the above code gives you enough reference.
TL;DR (after db structure?)
1- A text box with an a href as the submit.
2- table update is done on-the-fly (no reloads). Ajax.
3- Be able to buy more than 1 item at a time without page reloads
4-no help with php code required unless necessary.
I'd appreciate any sort of help.
Here's a very rough solution for you. In your while loop you could attach the item's database id to the id of the element:
while($_row = mysql_fetch_assoc($query)){
echo out name...
<input id="purchaseAmount{$_row->id}" type="text" name="value_to_buy" />
<a id="purchaseButton{$_row->id}" href="#" class="buy">Buy</a>
}
Then bind a javascript function to your "Buy" link which will make an AJAX request:
$('.buy').bind('click', function() {
// Grab the item id and amount
var itemId = $(this).attr('id').substring(14);
var itemAmount = $('purchaseAmount' + itemId).val();
$.ajax({
url: 'someurl/purchaseItem.php',
data: { item: itemId, amount: itemAmount },
success: function(data) {
// Update the player's gold and inventory on screen
}
});
});
The "purchaseItem.php" file could return a simple JSON object that holds the player's current gold and item amount for the inventory. Or you could return HTML, depending on how your page is setup.
Some time ago, I had project in which I had to do sort of a CMS just for news management, add, edit, delete, etc. As Satya commented, the way is with AJAX if you want to do it nicely.
What I did was a loop, just like yours, for each row fetched with PHP mysql_fetch_assoc add a tr in a table (yeah, I know, tables...). I know that you didn't wanted PHP help, but I think this will help you.
$res=mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
foreach ($row as $col => $val) {
if ($col != "column you dont display or isn't 'ID' column" && $col != "another column you dont display, and so on") {
if ($col == "ID") $id = $val;
//use this to echo values in table/tr/td/div/span or whatever you use to display values
if ($col == "gold") {
echo 'whatever you want to echo using the gold value';
}
if ($col == "name of last column you are displaying") {
echo 'whatever you display for that column';
echo '<input type="text" value="Introduce quantity">';
//If you are on HTML5 you could just use id="{$id}" as it will be easier
echo '<a href="#" class="buy" id="i_{$id}" value="Introduce quantity">';
}
}
}
One of the most important things here is to keep track of the ID of each item, this way you can relate them when sending the POST request to the server.
I recommend you to use jQuery for that matter, it's very easy to use
<script type="text/javascript">
$(document).ready(function () {
$(".buy").click(function(e) {
e.preventDefault();
// You get the id attribute of the button clicked, which contains the
// item ID. Then you substr the string to get just the id number. Example:
// The id of the clicked element is "i_2254" you use substr to get just the
// 2254 and send it to the php that process the buy
// If you choose the HTML5 id form I said above in the PHP, then var id=$(this).attr("id")
var id = $(this).attr("id").substr(2);
$.ajax({
type: "POST",
url: "buy_item.php",
async:false,
data: "itemID="+id,
success: function(data) {
// Here is where the magic occurs, this is what happens when you
// get the response, here is where you update the
// inventory, quantity, etc WITHOUT reloading.
// The variable data is the response of the server
// you just echo what you need on buy_item.php, and
// that will be data here
// A simple example is to change the value of an input
// with id="gold", you echo gold on php and...
$('#gold').val(data);
}
});
});
});
});
</script>
In the buy_item.php is where you UPDATE the gold values of the table, and add the item to the item table. Use $_SESSION variable to store user session name and update the gold and items of that user.
I suggest you to investigate about AJAX and jQuery(optional), it would help a lot!
I think basically this will solve your problem, and I hope for an invitation for the game :P

Categories