'Was this review helpful?' button PHP Jquery Ajax - php

I am building a review system with php jquery and ajax. I have written the following code already for the 'Was this review helpful?' button:
<input type='button' value='Yes' onClick = 'myCall()'
style='background-color:#556B2F;color:white;padding:2px; cursor:pointer'
name='help' />
<input type='hidden' id='randomdirectory' value='$g' name='ids'/>
$g is the variable I assigned to the id of the review which is stored in a database. The ajax script is this:
<script>
function myCall() {
var ids = $('#randomdirectory').val();
var self = this;
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('#ques1').hide();
}
});
}
and the code in the "rev.php" file is this:
<?php
include 'includes/db.php';
$q = $_POST['ids'];
if ($q != ""){
$result = mysql_query("SELECT * FROM table where id='$q'");
while($row = mysql_fetch_array($result))
{
$finalproduct = $row['numberofhelpfulvotes'];
$finalproduct1 = $finalproduct + 1;
}
mysql_query("UPDATE table SET numberofhelpfulvotes='$finalproduct1' WHERE id ='$q'");
}
?>
The problem is when I have multiple reviews on the page. When you click any of the "Yes" buttons on any of the reviews, the first review displayed gets the vote added to it, not the actual review where the button was clicked. Also when the button and text is hidden after the ajax call, the first review button and text is hidden, not the review where the button was clicked. Also a black line appears on the bottom of the page.
Any solutions to these problems will be greatly appreciated.

Thanks for all reply's. I ended up doing this which works perfectly for me:
<script>
$(function() {
$(".button").click(function() {
var ids = (this.id);
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('.' + ids).hide();
}
});
});
});
</script>
and this as the html:
<div class='$g'><font size='2' color='black'>Was this review helpful?</font> <input type='submit' value='Yes' onClick = 'myCall()' style='background-color:#556B2F;color:white;padding:2px; cursor:pointer' name='help' id='$g' class='button' /><input type='hidden' id='randomdirectory' value='$g' name='ids'/>
The php stayed the same, but I am going to update it to make it more secure.

Related

need help for proper way to write codes for create "loadmore" button and "like" button for posts

I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>

php handler not responding when using mutliple form with same handler

I use the following code to output a table with FAQ.
// get faq
global $wpdb;
$faq = $wpdb->get_results("SELECT ID, q, a, cat, quality, active FROM ce_faq");
foreach ($faq as $i) {
echo
'<div>
<a id="'.$i->ID.'" class="question" href="#">'.$i->q.'</a>
</div>
<div id="a'.$i->ID.'" class="answer">
<p>'.$i->a.'</p>
<form method="POST" id="form'.$i->ID.'">
<input type="hidden" value="'.$i->ID.'" name="faq_id"></input>
<input type="hidden" name="action" value="ce_faq_quality"/>'
.wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ).
'<p><b> Was this answer usefull? <input type="radio" name="quality" value="1" class="quality_radio"> yes </input><input type="radio" name="quality" value="-1" class="quality_radio"> No </input> </b></p>
</form>
</div>';
}
echo '<div id="feedback">feedback</div>';
I use jQuery().slidetoggle to toggle the answers when somebody clicks on the question. I want to enable end-users to give feedback on the questions with a simple yes or no question. The form should be submitted when one of the radio buttons is selected. the trigger jQuery('.quality_radio').click is working and also the formid is correctly fetched.
problem: The function ce_faq_quality(); is unfortunately not responding, when i use console.log(qu) i get for example 'faq_id=1&action=ce_faq_quality&name_of_nonce_field=7dd1d930af&_wp_http_referer=%2Ffaq%2F&quality=1', which seems to be correct to me. I also get the alert 'this is working'. The php handler doesn't seem to work however. the div feedback turns 0 (instead of 'success php function') and also the query isn't performed (while I know it works for 120%). I am at a loss here...
solved: the handler wasn't accessible from the page i was working on...
jQuery('.question').click(
function(){
var id = this.id;
jQuery('#a'+id).slideToggle(350);
});
jQuery('.quality_radio').click(
function(){
var formid = jQuery(this).closest('form').attr('id');
var formid = '#'+formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formid){
var qu = jQuery(formid).serialize();
console.log(qu);
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success:function(data){
jQuery("#feedback").html(data);
alert('this is working');
}
});
return false;
}
This is the php function i use to process the form.
add_action('wp_ajax_ce_faq_quality', 'ce_faq_quality');
add_action('wp_ajax_nopriv_ce_faq_quality', 'ce_faq_quality');
function ce_faq_quality(){
$quality = 1; //$_POST['quality'];
$faq_id = 1; //$_POST['faq_id'];
global $wpdb;
$wpdb->query($wpdb->prepare("UPDATE `ce_faq` SET `quality`= `quality` + $quality WHERE id = $faq_id"));
echo 'succes php function ';
die();
}
Your formid variable falls out of scope in the ajaxSubmit function. You should instead try:
jQuery('.quality_radio').click(
function() {
var formid = jQuery(this).closest('form').attr('id')
var formid = '#' + formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formId) {
var qu = jQuery(formid).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
So that you pass the formid to the ajaxSubmit function.

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

on checkbox click some php code to be executed in the same page

I have form inside the while condition in echo because in while condition, some value comes from the database and according to each row, user perform an action in the form.
In the form, the checkbox is onclick of the checkbox, i want the PHP code to be executed in the same page which will update the database.
echo "<tr><td>Assign employee ID</td><td>Task Assign</td><td>Date of Assigning Task</td>
<td>Given Task time</td><td>Time of given task</td><td colspan=3>Read message</td></tr></tr>";
$message=mysql_query("select * from message where receiver_id='$myid' and is_read != 1 ");
while($row=mysql_fetch_array($message))
{
$sender_id=$row["sender_id"];
$receiver_id=$row["receiver_id"];
$task_assign=$row["message"];
$date=$row["date"];
$time_of_given_task=$row["time"];
echo "<tr>
<td>".$sender_id."</td><td>".$receiver_id."</td><td>".$task_assign."</td>
<td>".$date."</td><td>".$time_of_given_task."</td><td>
<form action='message_to_read.php?date=$date&time=$time_of_given_task&receive=$receiver_id' method=post>
<input type=checkbox value=checked name=check onclick=foo();></td>
</form>
</td>
</tr>";
}
echo "</table>";
function foo()
{
$todaydate=$_REQUEST["date"];
echo $todaydate;
$time_of_given_task=$_REQUEST["time"];
echo $time_of_given_task;
$empid=$_REQUEST["receive"];
echo $empid;
$test2=mysql_query("update message set is_read='$update' where receiver_id='$empid' and date='$todaydate' and time='$time_of_given_task' ");
}
Looks like an AJAX problem to me. If you are using JQuery simply use AJAX built in functionality.
$(document).on('change', '#YOUR_CHECKBOX', function() {
if ($(this).is(':checked')) {
//if checkbox is checked do ajax call
$.ajax({
type: 'post',
url: URL_TO_YOUR_PHP_SCRIPT,
data: { OPTIONAL : DATA },
success: function(result) { }
});
}
});
change event would be better than click event in this situation

update sql record using javascript

I have a simple form before:
<form method="post" action="firstbillsubmitbal.php?id=#COL1#">
<input name="currentbal" type="text" id="currentbal" class="input-mini" />
<input type="submit" id="submit" value="Save" class="btn btn-success" />
</form>
Which calls this page for processing firstbillsubmitbal.php
$dealID = $_GET["id"];
$currentbal = mysql_real_escape_string(stripslashes($_POST['currentbal']));
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID'") or die (mysql_error());
It was working fine for single transactions. But I need to edit it a bit since I am displaying my data in a table now. I now have this js code when I click on a btn on my table per row, passes my row_id and currentbal calue, I got it working but I would like to know from this js code how do I process my form?
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var r=confirm("Are You Sure You Want To Proceed?");
if(r==true) {
alert("Record is saved");
} else {
alert("Cancelling Transaction");
}
}
The js code has two variables only at the moment which is
row_id = this is basically the ID of the db row and
currentbal = which is the value I want to upload to my db
My question basically is how do I call my firstbillsubmitbal.php file and what/how do I edit on my php file so that my row_id and currentbal are uploaded on my db since I am no long using POST.
Thank you for the replies. So I went thru some SO answers and some tutorials I found on google and this is what happened to my js code.
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var dealID = row_id;
//organize the data properly
var data = 'currentbal=' + currentbal.val() + '&dealID=' + dealID.val();
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
data: data,
cache: false,
success: function() {
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
And this is what happened to my firstbillsubmitbal.php page
$dealID = $_GET['dealID']
$currentbal = $_GET['currentbal']
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID' LIMIT 1") or die (mysql_error());
But nothing happens when I click on the button to call my function. What am I missing?
Also, here is how I call my function. #COL1# is my row ID value.
Update
Are your function getting called correctly with row_id data ?
if so then might be this will give you a trick,
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var dealID = row_id;
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
//pass data like this
data: {currentbal:currentbal.val(),dealID: dealID.val()},
cache: false,
success: function(data) {
if (data=="1")
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
and in php file
$dealID = $_GET['dealID']
$currentbal = $_GET['currentbal']
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID' LIMIT 1") or die (mysql_error());
echo "1" ; // if update successful
else echo "0" // if update unsuccessful
HTML :
<form method="post" action="firstbillsubmitbal.php">
<input name="currentbal" type="text" id="currentbal" class="input-mini" />
Update
</form>
JS :
function funcEdit(row_id){
var currentbal = $("#currentbal").val();
//organize the data properly
var data = 'currentbal=' + currentbal + '&dealID=' + row_id;
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
data: data,
cache: false,
success: function() {
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
Hope it works for you!

Categories