Updating Database Using Javascript - php

Hopefully this will be the last question I need to ask about this..lol.. I cant be too far of the working solution(hopefully..lol). In reference to this question:
Pass data to database using javascript Onclick
I am trying to pass a value to the database using javascript. Below is the code i am using. And just for visual aid, Ive included a screenshot of what this outputs. Hopefully it will help to explain what im trying to achieve also. The problem im having is the javascript "Vote" link pretty much does nothing...lol... u click it, and nothing happens. Preferably i would like the links text to simply change to "You Voted!" once the link has been clicked, and data sent/recieved, but an alert will be fine, as long as i can get this to work and update the database.
Thanks everyone:)
<?php if(isset($_POST['score'])) {
mysql_query("INSERT INTO score (score_count) VALUES ($_POST[score])");
} $user_id = uid();
$m = mysql_query("SELECT * FROM friends WHERE friend_user_id1 = '$user_id' AND friend_status != '0' LIMIT 15");
while ($t = mysql_fetch_array($m))
{
$fid = $t[friend_user_id2];
$f = mysql_query("SELECT * FROM users WHERE user_status != '' AND user_status_date != '0' AND user_id = '$fid' ORDER BY user_status_date ASC LIMIT 15") or die(mysql_error());
while ($rows = mysql_fetch_array($f))
{
$date = parse_date($rows[user_status_date]);
echo "<div style='margin: 5px;'><table><tr><td valign='top' style='width:55px;'><a href='page.php?id=$rows[user_username]'>";
_photo($rows[user_id]);
echo '</a></td><td valign="top"> <b>'.$rows[user_username].'</b> - <span style="font-size:7pt;">'.$date.'</span><span style="font-size:7pt;"> - Vote</span>
<br />'.$rows[user_status].'</td><td valign="top"></td></tr></table></div>';
}
}
?>
<script type="text/javascript">
function updateScore(answer, correct) {
if (answer == correct) {
$.get('index.php', {'score': '1'}, function(d) {
alert('Vote Accepted: ' + d);
});
}
}
</script>
Outputs:
alt text http://www.freeimagehosting.net/uploads/a7185475b8.png

Wow, where do I begin. Ok, I fixed up your code. Here's a list of the changes
Formatted code for legibility (you need some serious discipline here)
Sanitized inputs before using them in queries (prevents SQL injection)
Added string delimiters to associative array key lookups (prevents E_NOTICE errors)
Escaped potentially dangerous values before printing as HTML (prevents XSS)
Removed awkward echo statements and changed to HTML mode for large output strings instead
Updated javascript to use $.post() instead of $.get() since you read from the $_POST array at the top of the script.
Here's the code:
<?php
if ( isset( $_POST['score'] ) )
{
$result = mysql_query( "INSERT INTO score (score_count) VALUES (" . mysq_real_escape_string( $_POST['score'] ) . " )" );
echo $result ? 'Vote Succeeded' : 'Vote Failed: ' . mysql_error();
exit;
}
$user_id = mysql_real_escape_string( uid() );
$m = mysql_query( "SELECT * FROM friends WHERE friend_user_id1 = '$user_id' AND friend_status != '0' LIMIT 15" );
while ( $t = mysql_fetch_array( $m ) )
{
$fid = mysql_real_escape_string( $t['friend_user_id2'] );
$f = mysql_query( "SELECT * FROM users WHERE user_status != '' AND user_status_date != '0' AND user_id = '$fid' ORDER BY user_status_date ASC LIMIT 15" ) or die ( mysql_error() );
while ( $rows = mysql_fetch_array( $f ) )
{
$date = parse_date( $rows['user_status_date'] );
?>
<div style="margin: 5px;">
<table>
<tr>
<td valign="top" style="width:55px;">
<a href="page.php?id=<?php echo escapeForHtml( $rows['user_username'] ); ?>">
<?php _photo( $rows['user_id'] ); ?>
</a>
</td>
<td valign="top">
<a href="page.php?id=<?php echo escapeForHtml( $rows['user_username'] ); ?>" class="blue">
<b><?php echo escapeForHtml( $rows['user_username'] )?></b>
</a> - <span style="font-size:7pt;"><?php echo escapeForHtml( $date )?></span>
<span style="font-size:7pt;"> - Vote</span>
<br /><?php echo escapeForHtml( $rows['user_status'] ); ?></td><td valign="top">
</td>
</tr>
</table>
</div>
<?php
}
}
function escapeForHtml( $value )
{
return htmlspecialchars( $value, ENT_COMPAT, 'UTF-8' );
}
?>
<script type="text/javascript">
function updateScore(answer, correct)
{
if (answer == correct)
{
$.post('index.php', {'score': '1'}, function(d)
{
alert('Vote Accepted: ' + d);
});
}
}
</script>
After I got all that done, I could then clearly see that your success condition for the POST to actually take place is unknown to me. You compare answer to correct but this code snippet doesn't let me see where correct comes from. Once inside the updateScore() function I can see that answer is a reference to the HTMLAnchorElement that was clicked - but what is the source for the value sent into correct?
To be specific, I'm taking about this bolded part here
onclick="updateScore(this, correct)"
Edit!
Try this for a version of your function that updates the link after a successful vote
<script type="text/javascript">
function updateScore( answer )
{
if ( confirm( "Are you sure?" ) )
{
$.post('index.php', {'score': '1'}, function(d)
{
alert('Vote Accepted: ' + d);
$(answer).after("<span>You Voted!</span>").remove();
});
}
}
</script>

The first thing I notice, in your JavaScript code you are doing the Ajax request with $.get, and in your PHP code, you expect a POST variable if(isset($_POST['score'])).
So, if you use POST variables in the server side you should use $.post in the client side.

You're not sanitizing your inputs. Anyone, using your app or not, could send you a "score", and you'll blithely put it in your database. Or they could as easily send you a SQL injection attack, by posting with score the string "1); some attack here ; insert into score(score_count) values ( 2";

Related

PHP echo get value shows <br> tag

[The issue has resolved itself for some reason.]
I've had this piece of code for quite a while now with no issues whatsoever. Today I started getting to work and got an uncaught syntax error, telling me there was a stray "<". I located it and it's a piece of javascript code that gets the id value of the post you are looking at (on the forum).
The code is used for deleting a post using AJAX.
$('.deletePost').click(function() {
var delPost = confirm('Are you sure you want to delete this post?');
if (delPost == true) {
var xhttp = new XMLHttpRequest();
var getId = <?php echo $_GET['id'] ?>
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
location.replace('index');
}
}
xhttp.open('GET', 'deletepost.php?id=' + getId, true);
xhttp.send();
}
return false;
});
When loading up the actual website, the getId variable is <br >
This code is located in the 'footer.php' file, I use include to get it on every page on the website.
First off I use jQuery click to execute this, so the syntax error shouldn't really be a problem on other pages, as I made sure to not use the .deletePost class on anything on any of the other files. Second, it also needs the user to click OK and make the variable true, so to me this just makes no sense.
The biggest problem is that it makes all the other javascript code both above and below it useless.
(I'm not sure if any more code is relevant and I didn't want to make this too long, so please let me know if I need to include anything else.)
ID in $_GET['id'] is generated like so:
`
$sql = '
SELECT c.cat_name, c.cat_id, c.cat_description, t.topic_id, t.topic_by, t.topic_subject, t.topic_date
FROM categories c LEFT JOIN topics t ON c.cat_id=t.topic_cat
WHERE topic_date = ( SELECT MAX(t2.topic_date) FROM topics t2 WHERE t2.topic_cat = t.topic_cat ) AND c.cat_id<4
ORDER BY t.topic_date DESC
';
$result = mysqli_query($conn, $sql);
if (!$result) {
echo 'Could not display categories. Error: ';// . mysqli_error($conn);
} else {
if (mysqli_num_rows($result) == 0) {
echo 'No categories found in the database.';
} else {
echo '
<table>
<h3>Latest topics in categories</h3>
<tr>
<th>Category</th>
<th>Latest Topic</th>
</tr>
';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<td class="leftpart">
<h3>' . $row['cat_name'] . '</h3>' . $row['cat_description'] . '
</td>
<td class="rightpart">
' . $row['topic_subject'] . '<br>By <b>' . $row['topic_by'] . '</b>
</td>
</tr>
';
}
echo '</table>';
}
}`
This is the error. It appears in F12.
You have to use quotes around the php statement
like this. And make sure on the server side typecast the id value to integer
var getId = "<?php echo $_GET['id']; ?>";
first make sure that the GET parameter gets the id value correctly, check on the inspect element in browser , If your Id populated correctly from database it should be like this (I don't know your Ids and values)
<h3>correct cat name</h3>correct cat_description
And the GET parameter need a key "id" to get its value. The error saying that the "id" is not there at the URL as a GET parameter.
check the URL address also it should contain an "id" parameter
If your id from the database is some sort of string. enclose the string inside urlencode($row['cat_id']) function.
Other than that i don't see any errors. Pardon me if i misunderstood the question

issue in setting php page parameters and adding value in parameters using jquery

i am not getting value of qnty in query can anyone tell me what mistake i am doing. actually i am beginner so please correct this code and help me how i can add value of quantity box in php page parameter where i am getting other values using anchor tag.
<a id="btn1" href="sale.php?tag=<?php echo $_REQUEST['tag'];?>
&btn=&&pro_id=pro_id?> &name=pro_name;?>&price=price?>&">
<?php
if (isset($_REQUEST['pro_id'])) {
$txt = $_REQUEST['pro_id'];
$txt1 = $_REQUEST['price'];
$txt2 = $_REQUEST['name'];
$txt4 = $_REQUEST['bill'];
$txt3 = $_REQUEST['qnty'];
$d = date("d \- F \- Y ");
$cart = session_id();
$query = "INSERT INTO cart (cart_id, pro_id, pro_name, quantity, price, bill,date)
values ('$cart', '$txt','$txt2','$txt3', '$txt1','$txt1'*2, '$d' )";
mysql_db_query("medical_wholesale_store", $query);
header("location:sale.php");
}
?>
<script>
$(document).ready(function () {
$("#btn1").click(function () {
var qnty = $("#qty").val();
a = $("#btn1").attr("href") + "qnty=" + qnty;
});
});
</script>
Here is pic of adding php parameters and jquery function along with html code
There are several issues as far as I can see with your code.
In the recordset iteration loop you are including the same stylesheet.
You are repeating the input element with id qty ~ this is not valid
The a link has the id btn1 - this is also being repeated
The javscript function is also being repeated
The sum of column widths equals 99% rather than 100%
Because each is being repeated it will be impossible to know which element is being targeted properly. Hopefully what follows might help you solve your problems - no jQuery, just regular javascript ( I never use it )
That all said and done - your code is, I'm afraid to say, vulnerable to SQL injection and you should really think about migrating your code to use mysqli or PDO as they both support prepared statements which help mitigate against this danger! Good luck.
<?php
if ( isset($_REQUEST['pro_id'] ) ) {
$txt = $_REQUEST['pro_id'];
$txt1 = $_REQUEST['price'];
$txt2 = $_REQUEST['name'];
$txt4 = $_REQUEST['bill'];
$txt3 = $_REQUEST['qnty'];
$d = date("d \- F \- Y ");
$cart = session_id();
$query = "INSERT INTO cart ( `cart_id`, `pro_id`, `pro_name`, `quantit`y, `price`, `bill`, `date` )
values ( '$cart', '$txt','$txt2','$txt3', '$txt1','".( $txt1 * 2 )."', '$d' )";
/* Debug sql to ensure it looks OK - test in gui? */
echo $query;
mysql_db_query("medical_wholesale_store", $query);
header("location:sale.php");
}
/* execute sql query */
echo '
<table>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>stock</th>
<th>category</th>
<th>name</th>
<th>expiry</th>
<th>Quantity</th>
<th>link</th>
</tr>';
/* semi-pseudo code snippet */
while( $object = mysql_fetch_object( $result ) ){
$unique=uniqid();/* do not really need this */
echo "
<tr><!-- add content -->
<td>{$object->pro_id}</td>
<td>{$object->pro_name}</td>
<td>etc</td>
<td>etc</td>
<td>etc</td>
<td>etc</td>
<td>etc</td>
<td><input type='number' name='qty' value=1 style='width:80px'/></td>
<td>
<a class='salebttn' id='{$unique}' href='sale.php?tag={$_REQUEST['tag']}&btn={$unique}&pro_id={$object->pro_id}&name={$object->pro_name}&price={$object->price}&bill=UNKNOWN_ENTITY'></a>
</td>
</tr>";
}
echo '
</table>';
?>
<script>
/* Find all links that are used within your table that have a particular class */
var col=document.querySelectorAll('a.salebttn');
for( var n in col ) if( col[n].nodeType==1 ){
col[n].onclick=function(event){
event.preventDefault();
var el=typeof( event.target )!='undefined' ? event.target : event.srcElement;
var href=el.getAttribute('href');
/* need to find the value of the input qty so we traverse the dom to find it */
var qty=el.parentNode.parentNode.querySelectorAll('input[type="number"][name="qty"]')[0].value;
document.location.replace( href + '&qty='+qty );
};
}
</script>

mysql_query not fulfilling all specified parameters

so here is my code and I will tell you the problem after that:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat<?php echo $otherchatuser ?>').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>&numberofmessages=<?php echo $numberofmessages; ?>');
<?php
$subtractlogintime8 = time() - 600;
$data8 = mysql_query("SELECT * FROM loggedin WHERE username='$otherchatuser' and time > '$subtractlogintime'");
$numrows8 = mysql_num_rows($data8);
?>
if (<?php echo $numrows8; ?> == 1 )
{
document.getElementById("checkloggedin<?php echo $otherchatuser; ?>").innerHTML = '<img src="loggedin.png">';
document.getElementById("checkloggedin<?php echo $otherchatuser; ?>").style.marginLeft = '5px';
}
else
{
document.getElementById("checkloggedin<?php echo $otherchatuser; ?>").innerHTML = '';
}
}, 4000);
</script>
This is my code, which gets users who are logged in and also does other things. The problem that I am having occurs on this line:
$data8 = mysql_query("SELECT * FROM loggedin WHERE username='$otherchatuser' and time > '$subtractlogintime'");
The query successfully gets users from the database, but seems to be ignoring the "and time > '$subtractlogintime'");" part of the query. I have no idea why this is occurring and anyone who could possibly tell me what I have forgotten would be extremely appreciated. Thanks.
TIME is a reserved keyword in MySQL because of the TIME datatype. If it's not crashing, you would probably better off backticking your "TIME" keyword to refer to the field time.
$data8 = mysql_query("SELECT * FROM loggedin WHERE username='$otherchatuser' and `time` > '$subtractlogintime'");
Also note that, this code COULD be prone to SQL injection but we can't be sure without seeing the full code...

reform Jquery serialize li with php

i'm having trouble with the serialize Jquery fonction.
Fist, i create my li element with a php script, my data are written in my database (with "id", "contenu", "position") and catch it in my html :
<article>
<ul id="columns">
<?php
$req01=mysql_query("SELECT * FROM mytable ORDER BY id DESC");
$i=0;
while ($res01=mysql_fetch_array($req01)){
$i++;
echo '
<li class="column" id="listItem_'.$res01["position"].'" draggable="true">
<p>'.$res01["contenu"].'</p>
</li>';
}
?>
</ul>
</article>
And here's my script
$(document).ready(function() {
$("#columns").sortable({
column : '.column',
update : function () {
var order = $('#columns').sortable('serialize');
$("#info").load('structure-reform.php?'+order);
//alert("Data Loaded: " + order);
}
});
});
</script>
And here the way i update my DB when my li order is changing
foreach ($_GET['listItem'] as $position => $item) :
$list[] = "$position, $item";
$req03=mysql_query("UPDATE mytable SET position='".$position."' WHERE id='".$item."'");
$result = mysql_query($req03);
endforeach;
The thing is that, when i reload my page, my list isn't sorted the right way...How can i do in order to keep my list in the last order ?
Thanks !
Your logic wasn't correct.
replace your javascript with this:
$("#columns").sortable({ update: function() {
var order = $(this).sortable("serialize");
$.post("structure-reform.php", order);
}
});
replace your list html with this
<li class="column" id="listItem_'.$res01['id'].'" draggable="true" rel="'.$perso.'">
<p>'.$res01["contenu"].'</p>
</li>';
replace your while loop with this
$listingCounter = 1;
foreach ($_POST['listItem'] as $recordIDValue) {
$query = "UPDATE structure SET position = " . $listingCounter . " WHERE id = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo 'If you refresh the page, you will see that records will stay just as you modified.';
You'll either want to save the order parameter in PHP - store it in $_SESSION, or, set a cookie on the user's computer and retrieve that to sort.
why you don't use jquery ajax using $.ajax() ? may be there is problem with serialize(), have you tried this one ?
$("#columns").sortable({
column : '.column',
update : function () {
var order = $(this).sortable('serialize');
$.ajax({
url : 'structure-reform.php',
type: 'GET',
data: order,
success:function(res){
alert('Data Loaded '+res);
}
});
}
});
and fot the first time, you should debug your parameter from ajax request, using php it quite simple
<?php
print_r($_GET);
?>
then you can do the rest when you have know what paramter are given there

$.post() in jQuery not working

I'm making a rating system, and I have the following jQuery code on my index.php page:
<script type="text/javascript">
$(document).ready(function() {
$("[id^=rating_]").hover(function() {
var rid = $(this).attr("id").split("_")[1];
$("#rating_"+rid).children("[class^=star_]").children('img').hover(function() {
$("#rating_"+rid).children("[class^=star_]").children('img').removeClass("hover");
/* The hovered item number */
var hovered = $(this).parent().attr("class").split("_")[1];
var hovered2 = $(this).parent().attr("class").split("_")[1];
while(hovered > 0) {
$("#rating_"+rid).children(".star_"+hovered).children('img').addClass("hover");
hovered--;
}
$("#rating_"+rid).children("[class^=star_]").click(function() {
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
});
});
});
</script>
Basically theres a hover effect and then when you click on the star, it'll send a post request to send.php, with the info on the rating clicked and the id of the element. Below this script I have some PHP that looks like this:
<?php
$query = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($query)) {
$rating = (int)$row[rating];
?>
<div id="rating_<?php echo $row[id]; ?>">
<span class="star_1"><img src="star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span>
<span class="star_2"><img src="star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span>
<span class="star_3"><img src="star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span>
<span class="star_4"><img src="star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span>
<span class="star_5"><img src="star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span>
<div class="clearleft"> </div>
</div>
<br />
<?php
}
?>
And then of course I have some CSS to make it look nice.
The send.php file looks like this:
<?php
mysql_connect("localhost", "admin", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$rating = (int)$_POST['rating'];
$id = (int)$_POST['rid'];
$query = mysql_query("SELECT * FROM test WHERE id = '".$id."'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
if($rating > 5 || $rating < 1) {
echo"Rating can't be below 1 or more than 5";
}
else {
$total_ratings = $row['total_ratings'];
$total_rating = $row['total_rating'];
$current_rating = $row['rating'];
$new_total_rating = $total_rating + $rating;
$new_total_ratings = $total_ratings + 1;
$new_rating = $new_total_rating / $new_total_ratings;
// Lets run the queries.
mysql_query("UPDATE test SET total_rating = '".$new_total_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET rating = '".$new_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET total_ratings = '".$new_total_ratings."' WHERE id = '".$id."'") or die(mysql_error());
}
}
?>
There are 3 rating columns in the database table;
total_rating: total ratings (all the ratings added together).
rating: the current rating
total_ratings: the amount of ratings.
The problem is, if I change the $_POST['rating'] and $_POST['rid'] to $_GET and put the information int he url, for instance, send.php?id=1&rating=4, it works, and the database gets updated. However, when I press the stars, the database isn't updated. After messing around with the script I realised that the post must be working, however the id returns as 0.
To test this further I put this in the click function:
document.write(current_star+rid);
To see what was returned. The problem seems to be that the number that is returned is multiplied by the amount of times I hover over elements. So if I hover over maybe, 6 of the stars, then the current_star and ID will be repeated 6 times.
I feel like I'm so close to getting this to work, has anyone got any idea what's up with it? Thanks in advance.
And important thing to realize about jQuery's event handling is that it is registry-based, meaning that jQuery allows you to register multiple callbacks for any particular event, and it will invoke them in the order in which they were bound.
The reason you're seeing repeated current_star and id values is because you keep binding more and more events on every hover. This is because have your click() call inside your hover() call, therefore every time you hover, you will bind another click() event.
Try binding your click() event outside your hover event, using something like this:
$("[id^=rating_]").children("[class^=star_]").click(function() {
var rid = $(this).parent().attr("id").split("_")[1];
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
You also probably don't want to bind one hover() call inside the other, for the same reason.
I noticed you have used $_POST['rid'] instead of $_POST['id']. May be that's your problem.

Categories