how to update PHP variable with Jquery Ajax? - php

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}

If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});

You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Related

How to pass php array to ajax function

So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.
public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if($stmt->rowCount()>0){
foreach($results as $row){
echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';
//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}
Here is my Ajax call to send the info to my php file
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Then here is the php file that handles the call.
if(isset($_POST['upVoteIncrement'])){
$upVoteIncrement = $_POST['upVoteIncrement'];
$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();
$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}
Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!
If your using a loop to populate the row id, which it looks like you are here are your problems.
The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.
I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.
See if this helps:
PHP:
if(isset($_SESSION['user_session'])){
echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';
}
JS:
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Hope it helps!
I also want to point out that in the code below:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
echo $up;
exit();
}
}
You are exiting the script on the first iteration of the loop and you will only ever get one result back.
If you need to return an array of data it should look like this:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit();
}
}
echo json_encode($results);
You will then need to set your datatype to json instead of html.
The response in your ajax will now be an array. To see the array:
success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.
function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();
You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:
<input onclick="upVoteIncrementValue" />
Then your handler:
function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();
Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.

Select multiple rows into array and send them via AJAX

I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}

Trigger combo box events using jquery

I have this code:
$show_location = mysql_query("SELECT * FROM location ORDER BY location_code");
while($row_location = mysql_fetch_array($show_location))
{
$location_code = $row_location['location_code'];
$show_store = mysql_query("SELECT * FROM store_list WHERE location LIKE '%$location_code%'");
$count_store = mysql_num_rows($show_store);
while($row_store = mysql_fetch_array($show_store))
{
$store_name = $row_store['store_name'];
}
if($count_store==0)
{
$status = "Inactive";
echo '<option value="'.$location_code.'">'.$location_code.'</option>';
$sql1 = "SELECT description FROM location WHERE location_code=$location_code";
$result1 = mysql_query("$sql1");
$row1 = mysql_fetch_assoc($result1);
$description=$row1['description'];
}
else
{
$status = "Active";
}
//echo '<option value="'.$location_code.'">'.$location_code.'</option>';
}
What I want to do is to display the $description somewhere in the form. I have the kind of combobox where you can select as many as you can. I want to display each $description once a location is selected. But I dont know where to put the trigger. Can sombody help me? Thanks!
correct me if i am wrong, but will every location_code have one description right?
well there are two ways:
1) Easy but not so efficient way
Make an ajax call for every selected value.
$("#myDropDown").change(function (event) {
//alert("You have Selected :: "+$(this).val());
$.ajax({
type: "POST",
url: "ajax.php",
data: { type: "1", location: $(this).val() }
}).done(function( msg ) {
("#mydata").html(msg)
});
});
You can check for type == 1 on php side, get the description and print it
The above method will cause a ajax request for every selection
2) A bit complex, but efficient
First of all json_encode your location_code and description. It will become something like {code:"AU", description:"blah blah"}
Then use something like this
$("#sel").change(function(e){
//alert($(this).val());
var array = $(this).val();
for(key in array){
var json = JSON.parse(array[key]);
$("#desiptions").html(json.description);
}
});

AJAX Unique ID div color change per post if user logs in

There are many posts that are made by users, I want each post (or div in this case) to display the background color green or grey depending on the user status (logged in or not).
What I am trying to achieve is while idling on the page, you should see a user going online without refreshing the page
status.php
if (logged_in() === true){
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
echo "online";
}
}
}
}else {
echo "offline";
}
Main page
$res8 = mysql_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
datatype:"application/json",
type: 'GET',
success: function(data) {
if (data === "online") {
$('.status').css({background: '#40A547'});
} else {
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 5000);
});
</script>
<?php
}
}
}
echo '<div class="status">TEST</div></a></div>';
This code changes the background color of all the divs but I want it to only target the divs that correspond to the user that logged in (the creator of the post).
Not sure how to make the div have the dynamic styling using ajax.
Any help is much appreciated!
You can use the id user from the database to achieve this. Then add an id to the div corresponding to the user id. For instance :
Ajax Request in success :
$('.status #user'+ dataId).css({background: '#7f8c8d'});
In your HTML :
echo '<div class="status" id="user1">TEST</div></a></div>';
Edit
Your Main page (your AJAX request)
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.message === "online")
{
$('.status #user'+ data.userId).css({background: '#40A547'});
} else // data.message === "offline"
{
$('.status #user'+ data.userId).css({background: '#7f8c8d'});
}
}
});
//...
// HTML looks like...
echo '<div class="status" id="user1">TEST</div></a></div>';
echo '<div class="status" id="user2">TEST2</div></a></div>';
status.php
You set the dataType of your ajax request that you want return Json but it's unclea, your your status.php add the header content-type to json.
<?php
header('Content-Type: application/json'); // So add this
//...
$array = array(); // New variable which would be return as json
if (logged_in() === true) // Your online part
{
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
$array['message'] = 'online';
$array['userId'] = $row8['user_id']; // Here is the userId (adapt following your code)
}
}
}
}// Your offline part
else {
$array['message'] = 'offline';
}
echo json_encode($array);

How to increment a value in MySQL database with PHP?

I am trying this code, but it isn't working.
The main problem is in these variables or in the script given at the bottom.
<?PHP
$upVote1 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain1."'";
$upVote2 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain2."'";
$upIgnore1 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain2."'";
$upIgnore2 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain1."'";
?>
<img onClick='renderData1()' src="<?php echo $img1['Picture'] ?>" />
<img onClick='renderData2()' src="<?php echo $img2['Picture'] ?>" />
<!-- £££££££££££££££ SCRIPT HERE ££££££££££££££ -->
<script>
function renderData1()
{
document.write(<?php mysql_query("$update1, $upIgnore1") or die(mysql_error()); ?>);
};
function renderData2()
{
document.write(<?php mysql_query("$update2, $upIgnore2") or die(mysql_error()); ?>);
};
</script>
mysql_query does not support multiple queries. You will need to break it up into a single query per call.
You should set up some Ajax request to register user votes: This might give you some idea how to do it (using jQuery here):
Javascript function to execute on vote click event :
function upvote_picture(id){
$.ajax({
type: 'POST',
url: 'vote.php',
dataType: 'json',
data: {
picture_id: id
},
success: function (data) {
alert(data);
}
});
}
vote.php file:
<?php
// Any error or warning in this script will break JSON response !
function send_json($array)
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode($array);
exit();
}
// Add query execution status variables and messages here
$response = array();
$id = !empty($_POST['picture_id']) ? $_POST['pciture_id'] : FALSE;
if($id){
// Do you query here
if ( mysql_query(....)) {
$response['success'] = TRUE;
} else {
$response['success'] = FALSE;
}
} else {
$response['success'] = FALSE;
}
send_json($response);
?>

Categories