jQuery/AJAX post() - a few problems - javascript

I'm basically working on a site in which a user repeatedly clicks a button, increasing his score each time he clicks. I don't want the page to refresh between each click, so I'm using AJAX.
The problems I'm having currently are as follows:
When I try to set my javascript var to = <? echo $result['count']; ?>, it doesn't seem to work.
I don't understand how to correctly use PDO to UPDATE a MySQL table with a calculation in the query, such as $update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");. Is this the correct syntax for the calculation and is this the right way to do it in PDO?
Here is the code for my testing page which I am using for the clicking system:
<html>
<?php
$hostname = 'localhost';
$username2 = 'refrigerator';
$password = 'xxx';
$dbh = new PDO("mysql:host=$hostname;dbname=refrigerator", $username2, $password);
$username = $_COOKIE["user"];
$rows = $dbh->prepare("SELECT count FROM count WHERE username = '$username'");
$rows->execute();
$result = $rows->fetchALL();
$result['count'] = $count;
if(isset($_POST['action'])){
if ($_POST['action'] == 'increase'){
$update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");
}
}
?>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var count = <? echo $result['count']; ?>;
$("#update").click(function() {
$.ajax({
type: "POST",
url: "button.php",
data: {"action":"increase"},
success: function(update) {
count++;
$("#counter").html(+count);
}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"><? echo $result['count']; ?></div>
</body>
</html>
Thanks a lot, any help would be greatly appreciated. Even if you can point me in the right direction which will help me answer my questions, that would be awesome.
Thank you

You should have:
$count = $result['count'];
Instead of:
$result['count'] = $count;
The variable to the left of the = sign is what is receiving the assignment from whatever value is on the right of the = sign.
In your update statement you could, instead of using your count variable, could do:
$update = $dbh->execute("UPDATE count SET count=count+1 WHERE username='$username'");

Related

how to display output from PHP into HTML

basically what I've been trying to do is with PHP get a integer from MySQL after that is done, using JavaScript get the integer that PHP has and display it on HTML
<?php include('ConnectionCode.php');
$conn = mysqli_connect($svr, $usr, $pwd, $db) or die("Could not connect " . mysql_error());
$sql = "SELECT RetailPrice FROM WebHosting_PricingCOP WHERE id='32402' LIMIT 1";
$result = mysqli_query($conn, $sql);
$price = mysqli_fetch_array($result);
echo json_encode(number_format($price['RetailPrice'],0,".",","));
mysqli_close($conn)
?>
the code above will connect to the Database and get the value 59,347
now I'm trying to move this single value from PHP to Javascript in order to display it on HTML
<script type="text/javascript">
var PriceValue = "<?php echo json_encode($price) ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
I have gone through many discussions and options here and there and still cant figure out to make it work, when i try to run the html it doesn't display anything
I would greatly appreciate your input
Update:
You may also have a problem with using json_encode inside of "" quotes.
var PriceValue = "<?php echo json_encode($price) ?>";
Instead, use:
var PriceValue = <?php echo json_encode($price) ?>;
or
var PriceValue = <?php echo $price ?>; // if $price is not an object
Note:
To debug this, check the generated HTML source to see what JavaScript you are actually generating.
$price needs to be in the same scope when you try to generate JS.
http://phpfiddle.org/main/code/aeav-gb1w
<?php
$price = 2523525;
?>
<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
However, it is going to be preferable for you to use your PHP file as an API endpoint instead of mixing your PHP and JavaScript together.

PHP file ouputs the javascript code itself and not running

I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>

Javascript cant get value from PHP variable?

I want make data exist checker.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
?>
<script language="javascript" type="text/javascript">
var nick_exist = "<?php echo $nick_exist; ?>";
</script>
and this for $POST data
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function() {
if(nick_exist){
window.alert('Choose another nick please!');
}
});
I dont know where is the problem and my windows.alert is not running :(
thanks u
try like this get the count in php then return it to js:
NOTE: Please do not use mysql it is deprecated now start using mysqli or pdo.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
echo json_encode(array('count'=> $nick_exist));//send result to javascript
?>
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function(resp) {
var resp=JSON.parse(resp);
if(resp.count){
window.alert('Choose another nick please!');
}
});

Using php with database in a javascript

This code is when i hardcore the sentence "Have a nice day!", it will echo out the exact same line. My question is what if i want to retrieve sentence from the database, instead of hard-coding it.
<?php
$php_var = "Have a nice day!";
?>
<html>
<head>
<title>Hello</title>
</head>
<body>
<script>
var js_var = "<?php echo $php_var; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
</body>
</html>
I am suppose to do something like this is it? but it cant work. It printed out "SELECT * FROM sen WHERE id=1 ;" on the page.
<?php
$con = mysql_connect(localhost,root,password,database_name);
$php_var = "SELECT * FROM sen WHERE id=1 ;";
?>
<script>
var js_var = "<?php echo $php_var ; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
You're not executing the query and fetching the result. Something like this should work:
<?php
$con = mysqli_connect(localhost,root,password,database_name);
$php_var = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM sen WHERE id=1 LIMIT 1"));
?>
<script>
var js_var = "<?php echo $php_var['id']; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
Please be aware of some things:
Don't forgot error handling on the right way. (Not or die)
Check if the MySQL connecton was successfully made.
Possibility of MySQL injection
I've updated mysql_* to mysqli_*, this because mysql_* is deprecated and will being removed in the future.
My suggestion is that you create a Rest api with json response backend in PHP and then have a javascript frontend using like JQuery $get or something.
Remove ; from the query.
Use $php_var = "SELECT * FROM sen WHERE id=1";

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Categories