Multiple votes on one page - php

I have multiple images on the page. Each of the image has thumb up and thumb down and user is able to vote.
The problem is when user vote on the first image vote is changed but when he click on second image the vote is saved in database but isn't updated and changed on the page. When the page is refreshed the vote counter is updated.
Those are the button and votings for the image
$cookie_name = 'vote'.$row['image_id']; // Set up the cookie name
$value = $pdo->prepare('SELECT * FROM tc_tuto_yt_voting_system WHERE image_id= ?'); // BDD query, page ID values
$value->bindParam(1, $row['image_id'], PDO::PARAM_INT);
$value->execute();
$vote = $value->fetch();
echo '
if (isset($_COOKIE[$cookie_name])) {
echo '<div class="vote_up_done oneLine"></div>
<div class="numberVoted oneLine">'.$vote['positive'].'</div>';
}
else
{
echo '<div class="vote_up oneLine" id="voteUp"></div>
<div class="number oneLine" id="positive">'.$vote['positive'].'</div>';
}
if (isset($_COOKIE[$cookie_name])) {
echo '<div class="vote_down_done oneLine"></div>
<div class="numberVoted oneLine">'.$vote['negative'].'</div>';
}
else
{
echo '<div class="vote_down oneLine" id="voteDown"></div>
<div class="number oneLine" id="negative">'.$vote['negative'].'</div>';
}
Vote up&down is ajax driven so this is ajax part
function vote(type, value, image_id) {
var dataFields = {'type': type, 'value': value, 'image_id': image_id}; // We pass the 3 arguments, type: positive or negative ; value=1 ; pageId: here 5
$.ajax({ // Ajax
type: "POST",
url: "ad_vot.php",
data: dataFields,
timeout: 3000,
success: function(dataBack){
$('#' + type).html(dataBack); // Change the new value in id="positive" or id="negative" DIV
$('#voteUp').attr('class', 'vote_up_done oneLine'); // Change image by design/vote-up-done.png grey icon
$('#voteDown').attr('class', 'vote_down_done oneLine'); // Change image by design/vote-down-done.png grey icon
$('#positive').attr('class', 'numberVoted oneLine'); // Change the number's color by a grey one for the "positive" DIV
$('#negative').attr('class', 'numberVoted oneLine'); // Change the number's color by a grey one for the "negative" DIV
$('#message').html('<div id="alertFadeOut" style="color: green">Your vote is added!</div>'); // Diplay message with a fadeout
$('#alertFadeOut').fadeOut(3000, function () {
$('#alertFadeOut').text('');
});
},
error: function() {
$('#message').text('Vote fail. Please try again.');
}
});
}
UPDATE: vote and update
if( $result > 0) {
$query = $pdo->prepare('UPDATE tc_tuto_yt_voting_system SET '.$type.' = '.$type.' + 1 WHERE image_id= :image_id');
$query -> execute(array(
":image_id" => $_POST['image_id']
));
}
else
{
$type = $_POST['type'];
$value = $_POST['value'];
$image_id = $_POST['image_id'];
$query = $pdo -> prepare("INSERT INTO tc_tuto_yt_voting_system (image_id,positive,negative)
VALUES (:image_id, :positive, :negative)");
$query -> execute(array(
":image_id" => $_POST['image_id'],
":positive" => '0',
":negative" => '0'
));
$query = $pdo->prepare('UPDATE tc_tuto_yt_voting_system SET '.$type.' = '.$type.' + 1 WHERE image_id= :image_id');
$query -> execute(array(
":image_id" => $_POST['image_id']
));
}
$value = $pdo->prepare('SELECT * FROM tc_tuto_yt_voting_system WHERE image_id= ?'); // BDD query, page ID values
$value->bindParam(1, $_POST['image_id'], PDO::PARAM_INT);
$value->execute();
$result = $value->fetch();
$expire = 24*3600; // 1 day
setcookie('vote'.$image_id, 'voted', time() + $expire, '/'); // Place a cookie
echo $result[$type];

A better answer:
Don't store the votes in cookie. The user can change it, delete it, and he'll be able to vote again. Create a table in your db, and insert a row when the user votes.
Don't use onclick attribute. Use jQuery's .on/.bind/.click.
As tehy've already explained you, there cannot 2 or more elements on the page with the same id. You need to use classes.
As I've told you, don't use SET '.$type.' = '.$type.' + 1 unless you check what's $type's value. $_POST['type'] can be positive = 1; DROP TABLE tc_tuto_yt_voting_system;.
If registering is required for voting:
CREATE TABLE user_votes (
user_id INT(11) UNSIGNED NOT NULL,
image_id INT(11) UNSIGNED NOT NULL,
vote TINYINT(3) UNSIGNED NOT NULL
)
$user_votes = $db->prepare("SELECT image_id, vote FROM user_votes WHERE user_id = ?");
$user_votes->bindValue(1, $_SESSION["user_id"], PDO::PARAM_INT);
If not:
CREATE TABLE user_votes (
user_ip VARBINARY(16) UNSIGNED NOT NULL,
image_id INT(11) UNSIGNED NOT NULL,
vote TINYINT(3) NOT NULL
)
$user_votes = $db->prepare("SELECT image_id, vote FROM user_votes WHERE user_id = INET6_ATON(?)");
$user_votes->bindValue(1, $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR);
Then display the images, and votes:
$user_votes->execute();
$u_votes = [];
while ($vote = $user_votes->fetch())
$u_votes[$vote->image_id] = $vote->vote;
$images = $db->prepare("SELECT * FROM images");
$images->execute();
while ($img = $images->fetch())
{
$is_voted = isset($u_votes[$img->id]);
$vote = $is_voted ? ($u_votes[$img->id] ? "down" : "up") : "";
echo '<img src="'.$img->filename.'" />
<div class="vote" data-image-id="'.$img->id.'">
<div class="vote_down'.($vote == "down" ? " voted" : "").'"></div>
<div class="number positive">'.$img->positive.'</div>
<div class="vote_up'.($vote == "up" ? " voted" : "").'"></div>
<div class="number negative">'.$img->negative.'</div>
</div>';
}
JS:
$(document).on("click", ".vote .vote_down, .vote .vote_up", function(e)
{
if ($(e.target).is(".voted"))
return;
var that = $(this),
div = that.parent(),
type = that.is(".vote_up") ? "positive" : "negative",
id = div.attr("data-image-id");
$.ajax({
type: "POST",
url: "ad_vot.php",
data: {
tpye: type,
image_id: id
}
timeout: 3000,
success: function(dataBack) {
that.addClass("voted");
var number = div.find("."+type);
number.html(parseInt(number.html())+(type == "positive" ? 1 : -1));
$('#message').html('<div id="alertFadeOut" style="color: green">Your vote is added!</div>');
$('#alertFadeOut').fadeOut(3000, function () {
$('#alertFadeOut').text('');
});
},
error: function() {
$('#message').text('Vote failed. Please try again.');
}
});
});
PHP process:
$check = $db->prepare("SELECT 1 FROM user_votes WHERE image_id = ? AND user_id = ?");
$check->bindValue(1, $_POST["image_id"], PDO::PARAM_INT);
$check->bindValue(2, $_SESSION["user_id"], PDO::PARAM_INT);
//or
$check = $db->prepare("SELECT 1 FROM user_votes WHERE image_id = ? AND user_ip = INET6_ATON(?)");
$check->bindValue(1, $_POST["image_id"], PDO::PARAM_INT);
$check->bindValue(2, $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR);
$check->execute();
if ($check->rowCount())
die("Already voted.");
$vote = $_POST["type"] == "positive" ? 1 : 0;
$insert = $db->prepare("INSERT INTO user_votes VALUE(?, ?, ?)");
$insert->bindValue(1, $_SESSION["user_id"], PDO::PARAM_INT);
//or
$insert = $db->prepare("INSERT INTO user_votes VALUE(?, ?, INET6_ATON(?))");
$insert->bindValue(1, $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR);
$insert->bindValue(2, $_POST["image_id"], PDO::PARAM_INT);
$insert->bindValue(3, $vote, PDO::PARAM_INT);
$insert->execute();
$row = $vote == 1 ? "positive" : "negative";
$update = $db->prepare("UPDATE images SET ".$row." = ".$row." + 1 WHERE id = ?");
$update->bindValue(1, $POST["image_id"], PDO::PARAM_INT);

Related

Using jQuery autocomplete from PHP/MySQL

My database columns as shown below:
`matDes1` varchar(255) DEFAULT NULL,
`matCost1` int(255) DEFAULT NULL,
`matDes2` varchar(255) DEFAULT NULL,
`matCost2` int(255) DEFAULT NULL,
`matDes3` varchar(255) DEFAULT NULL,
`matCost3` int(255) DEFAULT NULL,
`matDes4` varchar(255) DEFAULT NULL,
`matCost4` int(255) DEFAULT NULL,
`matDes5` varchar(255) DEFAULT NULL,
`matCost5` int(255) DEFAULT NULL,
I have a dynamic table with add and remove rows inside my HTML file.
Inside this table I have textarea and input, whenever I start typing will show me suggestions, and if I select one, will automatically populate other fields.
Here below my textarea and input:
<textarea id='codeANCILLARY_1' class='codeANCILLARY' name="codeANCILLARY[]"></textarea>
<input type="text" id="mat50ANCILLARY_1" class="mat50ANCILLARY" name="mat50ANCILLARY[]" />
textarea Searching through matDes1 to matDes5. so no problem here.
the problem is when selecting to populate both field, only accepting matDes1 and matCost1 not the rest.
is there a way to use say something like if statement and say:
if (matDes1 selected) {
show matDes1 with matCost1
} else if (matDes2 selected){
show matDes2 with matCost2
}
and
so
on
i really dont know anymore what must i do. :(
The full jQuery and PHP files are:
$(document).on('keydown', '.codeANCILLARY', function () {
var id = this.id;
var splitid = id.split('_');
var count = splitid[1];
$('#' + id).autocomplete({
source: function (request, response) {
$.ajax({
url: "../../MY_PHP_PAGE",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 1
},
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label);
var id = ui.item.value;
// AJAX
$.ajax({
url: '../../MY_PHP_PAGE',
type: 'post',
data: {
id: id,
request: 2
},
dataType: 'json',
success: function (takesAnyVaribale) {
var len = takesAnyVaribale.length;
if (len > 0) {
var codeANCILLARY = takesAnyVaribale[0]['codeANCILLARY'];
var mat50ANCILLARY = takesAnyVaribale[0]['mat50ANCILLARY'];
var unitsANCILLARY = takesAnyVaribale[0]['unitsANCILLARY'];
$('#codeANCILLARY_' + count).val(codeANCILLARY);
$('#mat50ANCILLARY_' + count).val(mat50ANCILLARY);
$('#unitsANCILLARY_' + count).val(unitsANCILLARY);
}
}
});
return false;
}
});
});
"MY_PHP_PAGE"
include "config.php";
$request = $_POST['request'];
if ($request == 1) {
$search = $_POST['search'];
$query1 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes1 like'%".$search."%'";
$query2 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes2 like'%".$search."%'";
$query3 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes3 like'%".$search."%'";
$query4 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes4 like'%".$search."%'";
$query5 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes5 like'%".$search."%'";
$result1 = mysqli_query($con, $query1);
$result2 = mysqli_query($con, $query2);
$result3 = mysqli_query($con, $query3);
$result4 = mysqli_query($con, $query4);
$result5 = mysqli_query($con, $query5);
if ($result1 || $result2 || $result3 || $result4 || $result5) {
while ($row = mysqli_fetch_array($result1)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes1']);
}
while ($row = mysqli_fetch_array($result2)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes2']);
}
while ($row = mysqli_fetch_array($result3)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes3']);
}
while ($row = mysqli_fetch_array($result4)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes4']);
}
while ($row = mysqli_fetch_array($result5)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes5']);
}
}
echo json_encode($response);
exit;
}
if ($request == 2) {
$id = $_POST['id'];
$sql = "SELECT * FROM MY_COMPONENTLIST WHERE id=".$id;
$result = mysqli_query($con, $sql);
$AncillaryPricing_arr = array();
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$codeANCILLARY = $row['matDes1'];
$mat50ANCILLARY = $row['matCost1'];
//***************************
//***************************
$codeANCILLARY = $row['matDes2'];
$mat50ANCILLARY = $row['matCost2'];
.and
.so on
.until 5
//***************************
//***************************
$unitsANCILLARY = $row['units'];
$AncillaryPricing_arr[] = array(
"id" => $id,
"codeANCILLARY" => $codeANCILLARY,
"mat50ANCILLARY" => $mat50ANCILLARY,
"unitsANCILLARY" => $unitsANCILLARY
);
}
echo json_encode($AncillaryPricing_arr);
exit;
}
You really need a better database layout for exactly this reason. Split the matdes and matcost columns out into a separate table, linked by the component ID. You can have as many as you want, then, and it's much easier to search them. Instead of all your separate queries, you'd have something like
SELECT * FROM MY_COMPONENTLIST_MAT WHERE matDes like'%".$search."%' and component_id = " . $id
(except as a prepared statement) and it would find any of them. You can use a JOIN to get the rest of the information from the main component list.

PHP no results message still showing when posting data via ajax

I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.
This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $row["comment"];
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
}
}else{
$comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}
When the comment form is submitted it calls this function.
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
success: function (response) {
document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
$("#summernote").summernote("reset");
},
});
}else {
alert('Please enter a comment');
}
return false;
});
This is the post_comment.php page
if(isset($_POST['comment'])){
$comments = "";
$comment=$_POST['comment'];
$member_id =$_POST['member_id'];
$post_id =$_POST['post_id'];
if(isset($comment)) {
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = $entry_id
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $comment;
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
echo $comments ;
};
exit;
}
}
}else {
header("location: /blog");
exit;
}
If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.
Try return the response from the server as json. Plus remove the exit and header on your server side.
<script type="text/javascript">
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
dataType : "json",
encode : true,
success: function (data) {
$.each(data, function(index, element){
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>");
});
$("#summernote").summernote("reset");
$('.alert').empty();
},
});
}else {
alert('Please enter a comment');
}
return false;
});
</script>
Then your server side.
<?php
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$member_id = $_POST['member_id'];
$post_id = $_POST['post_id'];
$commentsArray = array();
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = ?
ORDER BY comm.comment_date DESC");
$sql->bind_param("ii", $post_id, $entry_id);
$sql->execute();
$sql_result = $sql->get_result();
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
$comment_date = date_create($row['comment_date']);
$commentsArray[] = array(
'comment' => $comment,
'post_date' = date_format($comment_date, ' l jS F Y H:i');
'comment_author' => $row['member_screen_name']
);
}
}
echo json_encode($commentsArray);
}
Also use the network tab on your browser console to see the response coming from the server.
it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.
update your code after the success
$('.alert-primary').hide()

error in updating mysql with $.post using jquery

i wanna have like for my blog posts, it should work like this: user will click on something and it increase that number by +1 and store it in data base, i have a column named post_like in my db. but after increase 0 to 1 (when i try to increase from 1 to 2 or more) i get error.
jquery:
$("#insert_like").click(function(e){
alert('s')
var like = $("#insert_like").val();
like += 1;
var post_id = $("#post_id").val();
$.post("./inc/like.php", {
like: like,
post_id: post_id
}, function(data, status){
$("#insert_like").text(data);
like = 0;
});
});
php:
<?php
if (isset($_POST['like'])) {
require_once 'db.inc.php';
$like = $_POST['like'];
$post_id = $_POST['post_id'];
$q = "UPDATE posts set post_like = ? WHERE post_id=? LIMIT 1";
$stmt = $conn->prepare($q);
$stmt->bind_param('ii', $like, $post_id);
$stmt->execute();
if ($stmt->affected_rows == 1) {
echo "$like";
} else {
echo "error: $stmt->error";
}
$stmt->close();
$conn->close();
} else {
header('Location: ../home.php');
}
html:
<p>Post like: <span id="insert_like" style="cursor: pointer"><?php echo $post_like ?></span> </p>
You can pass the Post Id from javascript and update the likes in the backend. Consider below example:
$("#insert_like").click(function(e){
$.post("./inc/like.php", {
post_id: $("#post_id").val()
}, function(data, status){
$("#insert_like").text(data);
like = 0;
});
});
and in the backend
<?php
if (isset($_POST['like'])) {
require_once 'db.inc.php';
$post_id = $_POST['post_id'];
$q = "UPDATE posts SET post_like = (post_like + 1) WHERE post_id = ?";
$stmt = $conn->prepare($q);
$stmt->bind_param('i', $post_id);
$stmt->execute();
if ($stmt->affected_rows == 1) {
// get the updated likes and return as response.
} else {
echo "error: $stmt->error";
}
$stmt->close();
$conn->close();
} else {
header('Location: ../home.php');
}
Hope this helps.

After button clicked, save to MySQL then display CSS highlight

I've got a Rating function that does as follows: Once a user clicks the +1 button, the rating goes up by 1, and saves to MySQL. What I'd like for it to do is once clicked, it changes
the background to a different color as shown below..
( What I'd like for it to do is the "once clicked" ) at the current moment it just updates the number with the background being white)
NOTE: I'm just asking for suggestions or some way to lead me in the right direction, thank you in advance.
Without being clicked:
Once clicked:
php/html form: to submit the +1
<div class="up vote" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
AJAX: to update the button
$(function()
{
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='voteUp')
{
$.ajax(
{
type: "POST",
url: "voting/up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
up_vote.php: submit from the ajax
$ip = $_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
if( $sth->fetchColumn() == 0)
{
$sth = $db->prepare("UPDATE posts set voteUp = voteUp+1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("INSERT into PostsRating (post_iD_fk, add_iP) VALUES (:id, :ip)");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
} else {
$sth = $db->prepare("UPDATE posts set voteUp = voteUp-1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("DELETE FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
}
$sth = $db->prepare("SELECT voteUp FROM posts WHERE post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$row = $sth->fetch();
echo $row['voteUp'];
}
In your success callback, why not just set a class to the parent and then update the .wrapper?
success: function(html)
{
parent.addClass("blue");
parent.find(".wrapper").html("+ " + html);
}
When the user refreshes the page and you want to continue to show the blue, you would simply:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $post_iD, ':ip' => $ip));
$class = ($sth->fetchColumn()) ? " blue" : "";
?>
<div class="up vote<?php echo $class; ?>" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
You can change the success function to add the color with .css("background-color","blue") or if you want to have it always blue if the vote_counter is higher than you can add this to the top of your code:
if (parseInt($("#"+id).children(".wrapper").text()) >= 1) {
$("#"+id).children(".wrapper").css("background-color","blue");
}
First of all, you can not have a class name with a space in it - it will be interpreted as two classes, up and vote.
Within the php you can echo something along the lines of (be sure to set dataType to json)
echo(json_encode(array("success"=>true)));
exit();
After which the jquery can handle the response:
function(result) {
var result_string = jQuery.parseJSON(result);
if(result_string.success) {
$(this).children(".wrapper").css("background-color", "blue")
}
}

ajax is not able to retrieve the parsed array by the PHP

I have a table sets in a popup window to show orders placed by a specific userID
<div id="shpcart">
<div id="shpop">
<table>
<thead>
<tr><th></th><th>Item name</th><th colspan="2">Price</th><th>shipping</th></tr><th>Quantity</th>
</thead>
<tbody id= "cartbody">
</tbody>
</table>
</div>
</div>
Here is the ajax to send the userID to the server
$(function(){
$(".prod_buy").click(function(){
var htmlId = $(this).attr('id');
var idarray = htmlId.split('-');
var itemId = idarray[1];
$.ajax({
type: "POST",
url: "tempselector.php",
data: {'proId': itemId }
}).done(function( msg ) {
jQuery.parseJSON(msg);
var output = jQuery.parseJSON(msg);
var htmlstring;
alert ("im running");
for(var index=0;index<output.length; index++){
var itmnam = output[index][1];
var itmpic = output[index][2];
var itmpr = output[index][3];
var itmdisc = output[index][4];
var itmdesc = output[index][5];
var itmshp = output[index][6];
var itmav = output[index][7];
htmlstring +="<tr><th><img src = '../cartimg/'"+itmpic+"></th><td>"+itmnam+"</td><td>"+itmdisc+"</td><td>"+itmshp+"</td><td>QTY</td></tr>";
}
$('#cartbody').html(htmlstring);
$("#shpcart").fadeIn();
});
});
and here is the PHP to fetch the order of the passed user id
<?php
session_start();
include('includes/config.php');
$uId = $_SESSION["uId"];
$prID = mysqli_real_escape_string($link,$_POST["proId"]);
//$pQty = mysqli_real_escape_string($link,$_POST["prQTY"]);
$pQty = 2;
//$prID = 4;
$sqlget= "SELECT * FROM vasplus_programming_blog_pagination WHERE id='".$prID."'"; // to find the selected item
$resultget = mysqli_query($link, $sqlget);
$itemget = mysqli_fetch_array($resultget);
$itemId = $itemget[0]; // store the selected id in var
$itemNm = $itemget[1];
$ITimage = $itemget[2];
$ITprice = $itemget[3];
//$ITdiscount =$itemget[4];
$ITdescription =$itemget[5];
$ITshipping =$itemget[6];
// $ITavailable = $itemget[7];
$ITcontrycod =$itemget[8];
$itemCol = $itemget[9]; // store the selected color in var
$itemSiz = $itemget[10]; // store the selected size in var
$ITqty = $itemget[11];
// we need to search the temp table to see if the selected item is there
$sqlsrch= "SELECT * FROM XXXXX WHERE product_id ='".$prID."' AND size = '".$itemSiz."' AND color = '".$itemCol."' AND user_id = '".$uId."' "; // if the item is in the temp table or not
$resultsrch = mysqli_query($link, $sqlsrch);
$itemsrch = mysqli_fetch_array($resultsrch);
echo $itemsrch;
if (isset($itemsrch)){
$adqty = $itemsrch[8];
$adqty ++;
$sqlupdate=" UPDATE XXXXXX SET qty='".$adqty."' WHERE product_id ='".$prID."' AND size = '".$itemSiz."' AND color = '".$itemCol."' AND user_id = '".$uId."' "; // update the qty of theexisting items in temp table
$resultupdate = mysqli_query($link, $sqlupdate);
}else {
echo " user id searching ";
$sqlisUsr= "SELECT * FROM XXXXXX WHERE user_id = '".$uId."' "; // check if the user has any item in the temp table
$resultisUsr = mysqli_query($link, $sqlisUsr);
$isUsr = mysqli_fetch_array($resultisUsr);
if (isset($isUsr)){ // if user has items in the cart
$getOrdId = $isUsr[2]; // get the order ID
$sqladdN=" INSERT INTO XXXXXXx (order_id, user_id, photo, express, qty, unit_price, country, color, size, product_id) VALUES ('$getOrdId', '$uId' , '$ITimage' , '$ITshipping' , '$pQty', '$ITprice' , '$ITcontrycod' , '$itemCol' , '$itemSiz' , '$prID' ) "; // insert the item with the existing order ID
$resultaddN = mysqli_query($link, $sqladdN); }else{ // user has no record in temp order
echo " else is running " ;
$ReNth = 0;
$oId = 1;
while ($ReNth != 1){
$sqlNewOiD= "SELECT * FROM XXXXXX WHERE order_id = '".$oId."'"; // generate a new order ID
$resultOsrch = mysqli_query($link, $sqlNewOiD);
$oIdsrch = mysqli_fetch_array($resultOsrch);
if (isset($oIdsrch)){
echo $oId++;
echo " order Id generated " .$oId;
}else{ // insert the new item with the new order id in the temp table
echo $oId."oId<br />" ;
echo $uId."uId<br />" ;
echo $ITimage."<br />" ;
echo $ITshipping."<br />" ;
echo $pQty."<br />" ;
echo $ITprice."<br />" ;
echo $ITcontrycod."<br />" ;
echo $itemCol."<br />" ;
echo $itemSiz."<br />" ;
echo $prID."<br />" ;
$sqladdNOID = " INSERT INTO XXXXXx (order_id, user_id, photo, express, qty, unit_price, country, color, size, product_id) VALUES ('$oId', '$uId' , '$ITimage' , '$ITshipping' , '$pQty', '$ITprice' , '$ITcontrycod' , '$itemCol' , '$itemSiz' , '$prID' ) ";
$resultaddNOID = mysqli_query($link, $sqladdNOID);
$ReNth = 1; // quit the searching for unique order id loop
}//end if
}//end while
}// end if
}// end if
// pars json code for the cart
$sql= "SELECT * FROM XXXXX WHERE user_id = '".$uId."'" ;
$result = mysqli_query($link, $sql);
while($item = mysqli_fetch_array($result)){
$array[] = $item;
}
echo json_encode($array);
?>
The problem is that the ajax is not able to retrieve the parsed array by the PHP. I see that the $uId being passed to the PHP and the PHP code works fine and $array has been fetched, but in return the ajax isn't able to read the $array .
please help me here
about the ajax method, you can try this code:
$.ajax({
url:'tempselector.php',
dataType:"json",
type:"GET",
data: {'proId': itemId },
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('body').append(XMLHttpRequest.responseText);
},
success:function(output){
var htmlstring;
for(var index=0;index<output.length; index++){
var itmnam = output[index][1];
var itmpic = output[index][2];
var itmpr = output[index][3];
var itmdisc = output[index][4];
var itmdesc = output[index][5];
var itmshp = output[index][6];
var itmav = output[index][7];
htmlstring +="<tr><th><img src = '../cartimg/'"+itmpic+"></th><td>"+itmnam+"</td><td>"+itmdisc+"</td><td>"+itmshp+"</td><td>QTY</td></tr>";
}
$('#cartbody').html(htmlstring);
$("#shpcart").fadeIn();
}
});
if unnecesary output is present then json can not be parsed, that's the issue. problem has been solved

Categories