getting number from php file with jquery ajax - php

I'm new to AJAX and jQuery. I'm trying to pass a number from unrate.php to be used as checkVal (as shown below). The file does a bunch of stuff but it only echos the number. When I add a alert(checkVal) it shows a invalid character and than the number I want. (I just want the number)...
ajax handler:
$.get("unrate.php?numb="+ID, function(checkVal){
if (checkVal == 1) {
number.innerHTML = addNumb + 1;
} else {
number.innerHTML = addNumb - 1;
}
});
unrate.php:
<?php
$uNum = $_SESSION['userNum'];
$ider = $_GET['numb'];
$sql = mysql_query("SELECT * FROM ratecheck WHERE ID =".$ider);
$checkRay = mysql_fetch_array($sql);
$checkVal = $checkRay[$uNum];
$sqlZ = mysql_query("UPDATE ratecheck SET `".$uNum."`=0 WHERE ID=".$ider)
or die(mysql_error());
$sqlB = mysql_query("SELECT * FROM sources WHERE ID =".$ider);
$sourceRay = mysql_fetch_array($sqlB);
$newRC = $sourceRay['ratecount'] - 1;
mysql_query("UPDATE sources SET ratecount =".$newRC." WHERE ID =".$ider)
or die(mysql_error());
if ($checkVal > 1)
{
$newpts = $sourceRay['points'] - 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] - 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
else
{
$newpts = $sourceRay['points'] + 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] + 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
echo $checkVal;
mysql_close();
?>

Extra characters at the beginning or end of your output are something you occasionally run into with php. I greatly endorse the comment that suggests looking at the raw output from the server. You might also want to think about these possibilities:
Invisible characters at the beginning or end of your script file. Use a text editor that will show you hidden characters (even a hex editor) and see if there are any. Also, you don't have to end your php script with ?> if you're not doing anything else past it. You can just leave it open, as that will prevent characters showing up at the end.
Check the character encoding that your script has. This might not be the solution, but some time ago I had a similar situation that went away when I changed the encoding to UTF8 without Byte-Order Mark. Try doing the same thing and see if that fixes it

Related

Show alert message if MySQL php query match one condition [duplicate]

This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance
Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.
you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}
Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks

Script to update mysql not working

Okay so I have a PHP script that makes a user an artist if vote is high enough. The first part of the script works (the part that does the voting). However, the second part of the script that makes a user an artist does not. It worked before on localhost but is not working on live server for some reason. Either the script has changed and I didn't notice it or there's something wrong with my server config.
I know I should be using mysqli but please don't mention that I am working on it.
To explain how the system works, a form on the voting page is posted to this script and it all runs from there.
There is no error in the error log. Updating the table for //make an artist if vote high enough just doesn't work.
Here's the script:
<?php
session_start();
include("../database.php");
$username = $_SESSION["username"];
$artistname = htmlspecialchars(mysql_real_escape_string($_POST['artistname']));
$trackname = htmlspecialchars(mysql_real_escape_string($_POST['trackname']));
$trackurl = htmlspecialchars(mysql_real_escape_string($_POST['trackurl']));
$flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload.
if(isset($_POST['yes'])){
//code runs if vote is yes
//check if user hasnt already voted on track
$result = mysql_query("SELECT username FROM voted WHERE voted='$artistname' AND trackname='$trackname' AND username='$username'")or die(mysql_error());
$check2 = mysql_num_rows($result);
if ($check2 != 0) {
echo('<t1>Sorry, you have already voted on this track. <b>Click next track.</b> </t1>');
$flag = $flag + 1;
}
//code runs if everything is okay
if($flag == 0){
mysql_query("UPDATE members SET vote = vote+1 WHERE artistname='$artistname'
");
echo '<t1><b>You liked the track "'.$trackname.'" by "'.$artistname.'"</t1></b>';
mysql_query("INSERT INTO voted (username, voted,trackname, yesno)
VALUES ('".$username."','".$artistname."','".$trackname."', 'yes')")
or die(mysql_error());
//make an artist if vote high enough
$vote = mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
if ($vote > 50) {
$artisturl = htmlspecialchars(mysql_real_escape_string(str_replace(' ', '',$_POST['artistname'])));
mysql_query("UPDATE members SET artist='Y', image1='../files/noprofile.jpg', artisturl='$artisturl' WHERE artistname='$artistname'
")or die(mysql_error());
mysql_query("UPDATE tracks SET artist='Y', artisturl='$artisturl' WHERE artistname='$artistname'
")or die(mysql_error());
//email user that has just been made artist
$result = mysql_query("SELECT * FROM members WHERE artistname= '$artistname'");
while($row = mysql_fetch_array($result)){
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($row['email'], FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($row['email'], FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
{//send email
$to = $row['email'];
$subject = "Congratulations! You're now an NBS artist";
$message = "Hi ".$row['artistname'].",
//message removed for condensed code
$from = "";
$headers = 'From:' . "\r\n" .
'Reply-To: ' . "\r\n";
mail($to,$subject,$message,$headers);
}
}
echo '<br><t1>You just made "'.$artistname.'" an artist! <b>Click here</b> to see their profile.</t1>';
}
}
}
You are missing two lines to convert the resource returned by mysql_query() into an integer for the comparison with 50.
$vote = mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
// Add these two lines
$vote = mysql_fetch_assoc($vote);
$vote = $vote['vote'];
if ($vote > 50) {
...however, all that section could be re-written to use 2 queries instead of 4:
//make an artist if vote high enough
$artisturl = mysql_real_escape_string(htmlspecialchars(str_replace(' ', '',$_POST['artistname'])));
// This effectively combines the first SELECT and the two UPDATEs into one query
$result = mysql_query("
UPDATE members m
LEFT JOIN tracks t ON m.artistname = t.artistname
SET
m.artist = 'Y',
t.artist = 'Y',
m.image1 = '../files/noprofile.jpg',
m.artisturl = '$artisturl',
t.artisturl = '$artisturl'
WHERE m.artistname = '$artistname' AND m.vote > 50
") or die(mysql_error());
// If this affected more than 0 rows, the user was made an artist
if (mysql_affected_rows($result) > 0) {
//email user that has just been made artist
$result = mysql_query("SELECT * FROM members WHERE artistname= '$artistname'");
// ...and so on
Note also that you should pass data through mysql_real_escape_string() as the last operation. So it should go mysql_real_escape_string(htmlspecialchars($data)) rather than the other way around.
I'll throw a dart at this one.
$vote = mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
if ($vote > 50) {
I don't believe you are converting your mysql_query result into a useful variable. Maybe you were using mysql_fetch_assoc or mysql_num_rows ? Num rows makes more sense if you have an individual record for each vote. If you are summing them up then you can use something like
$output = mysql_fetch_assoc(mysql_query("SELECT vote FROM members WHERE artistname='$artistname'")or die(mysql_error());
$vote = $output['vote'];
Something else to point out is that you aren't using mysql_real_escape_string on your inputs. This is very dangerous and it is strongly encouraged to use this function if you are facing the public internet.

Badge reason error

I'm trying to show badges on our system, badges are rewards/achievement to users. They show on their profile, the thing that works is the image/badge shows, but the badge reason doesn't.
I tried to do it like this
<?
$badgesql = mysql_query("select * from usr_badge where user = '$user'");
$user2 = mysql_query("select * from usr_users where username = '$user'");
$usr2 = mysql_fetch_array($user2);
$vipsql = mysql_query("select * from usr_vip where userid = '$usr2[id]'");
$vipcheck = mysql_num_rows($vipsql);
$badgecheck = mysql_num_rows($badgesql);
$checkit = $badgecheck + $vipcheck;
if($checkit==0)
echo("This user does not have any badges");
else
if($badgecheck!=0)
{
while($badge = mysql_fetch_array($badgesql))
{
echo('<a onclick="TINY.box.show({html:'Reason: '.$badge[reason].',animate:false,close:false,mask:false,boxid:'success',autohide:2,top:-14,left:-17})"><img src="'.$badge[badge].'" </a>');
}
}
//Display VIP Badges
if($vipcheck!=0)
{
$vipbadge = mysql_fetch_array($vipsql);
$vip1 = mysql_query("select * from usr_vipdb where id = '$vipbadge[vipid]'");
$vip2 = mysql_fetch_array($vip1);
echo('<img src="'.$vip2[url].'" alt="This user is a VIP!" />');
}
?>
but that code above doesn't work. It gives me an error when I try to view the page "Parse error: syntax error, unexpected T_STRING in /home/**/public_html/memb.php on line 167"
Can someone please tell me what I'm doing wrong or point me in the right direction?
Thanks in advance
That long line starting with echo is probably at fault -- the syntax highlighting here is broken with it, showing that you've probably mis-matched the quotes or something similar. (Break it apart. Make each small segment on its own line. You won't miss the mistake then.)
Here's your current code broken as I believe the interpreter will parse it:
echo('<a onclick="TINY.box.show({html:'
Reason: '.$badge[reason].'
,animate:false,close:false,mask:false,boxid:
'success'
,autohide:2,top:-14,left:-17})
"><img src="
'.$badge[badge].'
" </a>');
Note the line starting with the bare word Reason:. Since that's not the error you got, perhaps I guessed incorrectly, but there's no doubt that your current code is too messy.
I hope you are sanitizing your inputs ($user, $usr2[id]) and stored data ($badge[reason]) in code that is not shown here to protect against cross-site scripting vulnerabilities and SQL injection vulnerabilities.
Try this (fixed open/close quotes... i think)
<?
$badgesql = mysql_query("select * from usr_badge where user = '$user'");
$user2 = mysql_query("select * from usr_users where username = '$user'");
$usr2 = mysql_fetch_array($user2);
$vipsql = mysql_query("select * from usr_vip where userid = '$usr2[id]'");
$vipcheck = mysql_num_rows($vipsql);
$badgecheck = mysql_num_rows($badgesql);
$checkit = $badgecheck + $vipcheck;
if($checkit==0) {
echo("This user does not have any badges");
} else {
if($badgecheck!=0)
{
while($badge = mysql_fetch_array($badgesql))
{
echo('<a onclick="TINY.box.show({html: "Reason: '.$badge[reason].'",animate:false,close:false,mask:false,boxid:"success",autohide:2,top:-14,left:-17})"><img src="'.$badge[badge].'" /></a>');
}
}
//Display VIP Badges
if($vipcheck!=0)
{
$vipbadge = mysql_fetch_array($vipsql);
$vip1 = mysql_query("select * from usr_vipdb where id = '$vipbadge[vipid]'");
$vip2 = mysql_fetch_array($vip1);
echo('<img src="'.$vip2[url].'" alt="This user is a VIP!" />');
}
}
?>

Why does my if statement ignore my conditions?

I'm programming a random event system that happens to users when logged in and I put the below piece of code into my include file.
$tehchance = mt_rand(1,15);
if ($tehchance == "1"){
$thewin = 10;
mysql_query("UPDATE members SET Points = Points + $thewin WHERE Handle = '$members[Handle]'");
}
I also have this for another event:
if ($tehchance == "2"){
$thekhwin = 5;
$thexpwin = 10;
mysql_query("UPDATE members SET Points = Points - $thekhwin WHERE Handle = '$members[Handle]'");
mysql_query("UPDATE members SET XP = XP + $thexpwin WHERE Handle = '$members[Handle]'");
}
The code will work but sometimes when $tehchance is equal to something else other than 1 or 2, it'll just ignore my conditions and update the members table without satisfying the if statement. From testing, it'll randomly add points or subtract points. I printed the random number from $tehchance and it still adds points even when it isn't equal to 1 or 2. Then sometimes it doesn't do anything to the members table. Really confused here.
Any ideas?
Try using an if-then-else and debug that.
$tehchance = mt_rand(1,15);
if ($tehchance === 1){
echo 'doing 1';
$thewin = 10;
mysql_query("UPDATE members SET Points = Points + $thewin WHERE Handle = '$members[Handle]'");
} else if ($tehchance === 2){
echo 'doing 2';
$thekhwin = 5;
$thexpwin = 10;
mysql_query("UPDATE members SET Points = Points - $thekhwin WHERE Handle = '$members[Handle]'");
mysql_query("UPDATE members SET XP = XP + $thexpwin WHERE Handle = '$members[Handle]'");
} else {
echo 'doing nothing';
}
because you are comparing to a string : "1" instead of the number 1 (without quotes)

AJAX -> PHP not updating MySQL database consistently

So this is my early attempt at a Facemash style site in which the user will select one of two images, scoring a hit with the chosen image (the winner) and a miss with the unselected image (the loser) - both of which are recorded in a MySQL database.
The selected image is determined using javascript and uses jquery AJAX to notify a PHP script (backend.php) which updates the database.
This works absolutely correctly for updating the "hits" field. However, the "misses" are not consistently recorded. By this I mean that when the user clicks one image, the fact the other image has not been clicked is only sometimes shown in the database. As far as I can tell there is no pattern as to when the "miss" is and is not recorded, making it difficult to pinpoint where the problem lies.
I've checked the code over and over again and cannot understand why this is happening or what would be responsible for it, so I thought it would be best to post everything. I appreciate it's a lot to ask, but any explaination as to why I'm having this problem would be hugely appreciated, thanks.
<html>
<head>
<title>Facemash</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script>
</head>
<body>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
// Function to return path of photo
function photoPath ($person){
$query = mysql_query("SELECT photo FROM people WHERE id=$person");
$result = mysql_fetch_row($query);
$result = $result[0];
echo $result;
}
?>
<!--Image for personA-->
<div id=photoA identity="<?php echo $personA ?>"><img src="<?php photoPath($personA);?>"/></div>
<!--Image for personB-->
<div id=photoB identity="<?php echo $personB ?>"><img src="<?php photoPath($personB);?>"/></div>
<script type="text/javascript">
$('#photoA').click(function() {
var hit = $('#photoA[identity]').attr('identity');
var miss = $('#photoB[identity]').attr('identity');
$.post ("backend.php", {winner: hit} );
$.post ("backend.php", {loser: miss} );
location.reload(true);
});
$('#photoB').click(function() {
var hit = $('#photoB[identity]').attr('identity');
var miss = $('#photoA[identity]').attr('identity');
$.post ("backend.php", {winner: hit} );
$.post ("backend.php", {loser: miss} );
location.reload(true);
});
</script>
</body>
</html>
backend.php:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Recieve id of winner from index.php
$winner = $_POST['winner'];
// Recieve id of loser from index.php
$loser = $_POST['loser'];
// Lookup hits for winner and update by adding 1
function updateHits ($winner) {
$query = mysql_query("SELECT hits FROM people WHERE id=$winner");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET hits = $result WHERE id=$winner");
}
//Lookup misses for loser and update by adding 1
function updateMisses ($loser) {
$query = mysql_query("SELECT misses FROM people WHERE id=$loser");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET misses = $result WHERE id=$loser");
}
updateHits($winner);
updateMisses($loser);
?>
Thanks again.
Couple things.
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
This doesn't look like it will always guarantee they aren't the same person. The result of the second rand() could again return the same value as $personA
Instead of doing two queries to first select the misses and then increment it, why not make it one query?:
mysql_query("UPDATE people SET misses = misses + 1 WHERE id=$loser");
Lastly, in backend.php, instead of updating winners and losers even if you have only received one of the params, do an if else:
if($winner) {
updateHits($winner);
} else if ($loser) {
updateMisses($loser);
}
I think this will solve your problems.
As a matter of optimization, you should also combine your two POSTs into one.
Try changing your two functions to this and seeing if it will work. (If it doesn't I will just delete my answer.)
// Lookup hits for winner and update by adding 1
function updateHits ($winner) {
mysql_query("UPDATE `people` SET `hits` = hits + 1 WHERE `id`= '$winner'");
}
//Lookup misses for loser and update by adding 1
function updateMisses ($loser) {
mysql_query("UPDATE `people` SET `misses` = misses + 1 WHERE `id` = '$loser'");
}
This probably doesn't cause the problem, but you should only do one $.post and don't duplicate the same functionality in both click handlers.
JS:
$('#photoA, #photoB').click(function() {
var hit = $('#photoA[identity]').attr('identity'),
miss = $('#photoB[identity]').attr('identity');
$.post("backend.php", { winner: hit, loser: miss } );
location.reload(true);
});

Categories