PHP like/dislike button working only the first time - php

I'm trying to implement a like/dislike button on my page. I managed to get the button to work (it changes like to dislike and vice versa when clicked) and it also creates or deletes the like on the database table. The problem now is the counter of likes. It works only the first time i click the button, i.e. if initially there are 2 likes and i dislike the post the post shows 1 likes, but if I try to click again on it, it keeps showing 1 like and I have to reload the page to see it change to 2 likes.
This is what I have so far:
JQUERY
$(document).on('click', ".miPiace", function() {
trova = '';
commentoORisposta = '';
valCOR = '';
var comOrisp;
try{
trova = $(this).parentsUntil("#fermamiQui");
commentoORisposta = trova.find(".idCommento");
comOrisp = 'commento';
valCOR = commentoORisposta.val();
} catch(err){
trova = $(this).parentsUntil(".infoCommento");
commentoORisposta = trova.find(".idRisposta");
comOrisp = 'risposta';
valCOR = commentoORisposta.val();
}
valCOR = commentoORisposta.val();
if ($(this).hasClass('fa-thumbs-o-up')) {
$(this).removeClass('fa-thumbs-o-up');
$(this).addClass('fa-thumbs-up');
$.get( "lib/ottieniCose.php", { like: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
}else if($(this).hasClass('fa-thumbs-up')){
$(this).removeClass('fa-thumbs-up');
$(this).addClass('fa-thumbs-o-up');
$.get( "lib/ottieniCose.php", { remLike: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
};
});
PHP
if (isset($_GET['like'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->set_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->set_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
} elseif (isset($_GET['remLike'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->remove_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->remove_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
}
Other PHP file where there is the $commenti class
public function get_likes($id, $commento){
$idComm = 0;
$idRisp = 0;
$retVal = ($commento) ? $idComm = $id : $idRisp = $id;
if ($idComm != 0){
$query = "SELECT commento,
(SELECT COUNT(*) FROM likes
WHERE commento = {$idComm})
AS like_count FROM likes";
} elseif($idRisp != 0){
$query = "SELECT risposta,
(SELECT COUNT(*) FROM likes
WHERE risposta = {$idRisp})
AS like_count FROM likes";
}
$trovaQuanti = mysqli_query($_SESSION['connessione'], $query);
$trovaDavveroQuanti = mysqli_fetch_assoc($trovaQuanti);
if ($trovaDavveroQuanti == null) {
return '0';
}
return $trovaDavveroQuanti['like_count'];
}

You may want to try a normal $.ajax call. And turn off caching. Sometimes this causes an issue where you need to refresh to see the changes.
$.ajax({
type: 'GET',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(html){
trova.find('.numDiLikes').html('<p>' + data + ' likes</p>');
}
});

Related

JQUERY and AJAX Pagination and Calling Data

I am facing the following problem, I have a page of products with ajax pagination where users is able to select products in a form, the selected products save their id values in an array, but my problem is when the user goes to page 2 then he go back to page 1 he is able to choose the same product where I need to be the array ids unique, where user is able to select only the product 1 time even if he goes to page 2 or 3 and come back to previous pages
my ajax code:
$(".pageNumber").on("click",function(){
pageID = this.id;
var data_string = 'pageID='+pageID;
$.ajax({
type: "POST",
url: "loadData.php",
data: { "pageId" : pageID, "catid" : catid, "subid" : subid, "filter" : filter, "view" : view_type , "items" : itemArrayList},
cache: false,
success: function (result) {
$(".pageNumber").removeClass("number-page-active");
$("#"+pageID).addClass("number-page-active");
$("#results1").hide();
$("#results").html(result);
console.log(result);
if ($(".number-page-active").attr('id') == 1) {
$('#sub1').attr("style","display:none") ;
}
if ($(".number-page-active").attr('id') != 1) {
$('#sub1').attr("style","display:block") ;
}
if ($(".number-page-active").attr('id') == <?php echo $pageLast ?>) {
$('#add1').attr("style","display:none") ;
}
if ($(".number-page-active").attr('id') != <?php echo $pageLast ?>) {
$('#add1').attr("style","display:block") ;
}
}
});
The list of selected products are saved in array as follow:
$("#quotationSubmit").on("click",function(){
console.log(itemArrayList);
$("#itemListArray").val(itemArrayList);
});
var itemSelected = 0;
itemArrayList = [];
function image(divId) {
if (itemSelected < 0) {
itemSelected = 0;
}
var idDiv = 1;
for (idDiv; idDiv <= 100; idDiv++) {
var divDivId = "" + idDiv;
var divDivId0 = "" + idDiv;
if (divDivId === divId || divDivId0 === divId) {
break;
}
}
if ($("#quotation-form").css("display") === "block") {
if ($("#" + idDiv).hasClass("selected-div") === true || $("#" +
idDiv).hasClass("selected-div")) {
$("#" + idDiv).removeClass("selected-div");
$("#" + idDiv).removeClass("selected-div");
itemSelected--;
index = $.inArray(divId,itemArrayList);
itemArrayList.splice(index,1);
console.log(itemArrayList);
} else {
$("#" + idDiv).addClass("selected-div");
$("#" + idDiv).addClass("selected-div");
itemSelected++;
itemArrayList.push(divId);
console.log(itemArrayList);
}
if (itemSelected === 0) {
document.getElementById("quotationText").innerHTML = "Please Select an item";
} else {
if (itemSelected === 1) {
document.getElementById("quotationText").innerHTML = "You have 1 item Selected";
} else {
document.getElementById("quotationText").innerHTML = "You have " + itemSelected + " items Selected";
}
}
} else {
var imageMe = $("#" + divId).find('img').attr('src');
document.getElementById('image00').src = imageMe;
setTimeout(function () {
$(".modal-for-image").removeClass("left-modal-image");
}, 100);
}
}

e.preventDefault / return false breaks ajax script firing properly

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];

Ajax response return undefined

Hi I have been using ajax for many times. But I can't figure out whats the problem with my code this time. My head is blowing up since 2 days. I am using pusher for the realtime notification in CodeIgniter. Here's my code.
$(document).on("click", ".myonoffswitch", function () {
if (confirm("Sure!!! You want to Change the post status?"))
{
var thiss = $(this);
var prod_id = $(this).attr('id');
var status = $(this).attr('value');
var tdid = $(this).parent().prev().attr('class');
var td = $(this).parent().prev();
var adsstatus = $.ajax({type: "POST", dataType: "json", url: base_url + 'init/ads_status', data: {'prod_id': prod_id, 'status': status}});
$.when(adsstatus).done(function (adsstatuss) {
var msg;
msg = adsstatuss;
alert(msg.length);
var updated_status = msg[0].post_status;
alert(updated_status);
//alert(updated_status);
if (updated_status == "0" && tdid == prod_id) {
td.css("background", "#ccffcc");
td.text("On");
thiss.val(updated_status);
}
if (updated_status == "1" && tdid == prod_id) {
td.css("background", "#ffcccc");
td.text("Off");
thiss.val(updated_status);
}
});
}
});
ads_status (method in CodeIgniter)
public function ads_status() {
$prod_id = $_POST['prod_id'];
$status = $_POST['status'];
if ($status == "1") {
$new_status = "0";
$this->cmsdbmodel->ads_status($prod_id, $new_status);
$dat = $this->cmsdbmodel->get_updated_status($prod_id);
$ads_type = "product";
$emailreturn = $this->send_email_ads_status($prod_id, $ads_type);
//send user alert of product//
if ($dat[0]->post_status == "0") {
$lastInsertedId = $prod_id;
$modelNBrandId = $this->dbmodel->checkProductContainsAlert($lastInsertedId);
$getAlertEmail = $this->dbmodel->getAlertEmailFromBrandNModelId($modelNBrandId);
if (!empty($getAlertEmail)) {
foreach ($getAlertEmail as $alerts) {
$alertsEmail = $alerts->email;
}
}
$alertsPost = $this->dbmodel->getPostAlerts($lastInsertedId);
$sendPostAlerts = json_encode($alertsPost);
$encrytpEmail = hash('sha256', $alertsEmail);
$this->pusher->trigger($encrytpEmail, 'alerts', $sendPostAlerts);
}
//send user alert of product//
$realtime = $this->realTime_charts();
$realtime["post_status"] = $dat[0]->post_status;
$realtime["emailres"] = $emailreturn;
$data = $realtime;
$this->pusher->trigger('recent_activity', 'new_event1', $data);
echo json_encode($data);
}
}
Here I want to trigger event in pusher as well as echo json object. But in ajax, response is undefined. Also in console I can see json but when alerting the reponse it says undefined. Wheres problem in my code. Please help me.

Ajax call doesn't return data after echoed

The ajax call successfully update the record but doesn't return the string of echo. This script was working before but might be because of some upgrade it stops working. It is working fine on my local system but when I move it to bluehost server then it does not work.
Here is my Ajax call:
// call to ajax script to update site
function autopost_update_site() {
// get base directory url
var baseDir = jQuery('#baseDir').val();
var id = jQuery('#site_id').val();
var site_name = jQuery('#site_name').val();
var site_url = jQuery('#site_url').val();
var is_active;
if ( jQuery('#active_radio').is(':checked') ){
is_active = '1';
} else {
is_active = '0';
}
var username = jQuery('#login_username').val();
var login_pass = jQuery('#login_pass').val();
// call to ajax script to update script
jQuery.ajax( {
type: "POST",
url: baseDir + "/autopost_ajax_actions.php",
data: "id=" + id + "&site_name=" + site_name + "&site_url=" + site_url + "&is_active="+ is_active + "&username=" + username + "&login_pass="+login_pass +"&action=update_site",
beforeSend: function() {
jQuery('#update_site_button').attr("disabled", true);
// shortcode edit button
jQuery('#update_site_button').html('Updating...');
// admin page edit button
jQuery('#update_site_button').val('Updating...');
},
complete: function() {
jQuery('#update_site_button').attr("disabled", false);
// shortcode edit button
jQuery('#update_site_button').html('Update');
// admin page edit button
jQuery('#update_site_button').val('Update');
},
success: function(data) {
alert("Result: " + data); // NOTHING IS HAPPENING HERE, NO ALERT DATA
if (jQuery.trim(data) === "success") {
alert("Site updated.");
// refresh page
window.setTimeout('location.reload()', 200);
} else {
alert("Some error occured, Please try again.");
}
}
});
}
Here is my custom php script for ajax actions:
// update site
if ( $_POST['action'] == 'update_site' && isset ($_POST['id']) ) {
// collect site data
$site_name = $wpdb->escape($_POST['site_name']);
$site_id = intval($wpdb->escape($_POST['id']));
$site_url = $wpdb->escape($_POST['site_url']);
$username = $wpdb->escape($_POST['username']);
$login_pass = $wpdb->escape($_POST['login_pass']);
$is_active = $wpdb->escape($_POST['is_active']);
$query = $wpdb->prepare("UPDATE " . $autopost_sites_table_name . " SET site_name = %s, site_url = %s, username = %s, login_pass = %s, is_active = %s WHERE id = %s", $site_name, $site_url, $username, $login_pass, $is_active, $site_id);
#$log->LogDebug($query);
// execute query
$result = $wpdb->query($query);
#$log->LogDebug($result);
if ( $result !== FALSE || $result !== 0) {
// return success
$response = "success";
#$log->LogDebug($response);
echo $response; // THIS RESPONSE IS NOT SHOWING ON AJAX SUCCESS
} else {
$log->LogError("Failed to update site with ID: " . $_POST['id']);
echo "Failed to update site.";
}
}
Can anyone tell me what is missing?
Change data as follows
data:{
id:id,
site_name:site_name,
site_url:site_url ,
is_active:is_active ,
username:username,
login_pass:login_pass,
action:"update_site"
}
As It is mentioned that the script is working great on local but not working on server. So it was some server issue and I was getting error for "Access-Control-Allow-Origin" in chrome network.
I just added
header('Access-Control-Allow-Origin: *');
to my ajax action script and it worked! Thanks
after
echo $response;
put
die();
See http://codex.wordpress.org/AJAX_in_Plugins
In the example it says:
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}

passing a javascript variable to a php function and quoting it correctly

Im using Zend Framework ..in one of my phtml file's i have this code
<script>
function foobar(id,type){
var idarray = <?php AppNamespace_General::getparentids( ?>id, type<?php ) ?>; // here the id and type are from js
//the php function returns a json array to the js variable
......
location.href = baseurl +'/somepage/id/'+id;
}
How can i correctly pass the js elements to the php function
The php function(Already thought of doing it via ajax..its quite complex)
public static function getparentids($id, $type, $elmarray = '') {
if (empty($elmarray)) { //avoiding redeclaration of array
$elmarray = array();
}
switch (strtolower($type)) {
case 'group':
case 'product':
case 'specification':
$gp_handler = new PackAssist_Model_DbTable_Groups();
$q = "SELECT * FROM t_groups WHERE group_id = $id";
$sql = $gp_handler->getAdapter()->query($q);
break;
case 'part':
$pt_handler = new PackAssist_Model_DbTable_Parts();
$q = "SELECT * FROM t_parts WHERE part_id = $id";
$sql = $pt_handler->getAdapter()->query($q);
break;
}
$result = $sql->fetchAll();
$i = 0;
if (count($result) > 0) {
foreach ($result as $row) {
if (isset($row['group_parent_id']) && $row['group_parent_id'] != 0) {
if (in_array($row['group_id'], $elmarray)) {
$e = $row['group_parent_id'];
} else if ($row['group_parent_id'] != 0) {
$e = $row['group_id'];
}
} else if (isset($row['part_group_id'])) {
$e = $row['part_group_id'];
} else if ($row['group_parent_id'] == 0) {
break;
}
if (isset($e) && !empty($e)) {
array_push($elmarray, $e);
}
self::getparentids($e, 'group', $elmarray);
$i++;
}
} else {
array_push($elmarray, $id);
}
array_pop($elmarray); //removing the group of super parent group which we dont need
if ($i == 0) { // just encode the array only once
echo json_encode(array_reverse($elmarray));
}
}
If you use jQuery, you can do the following to execute the JSON request:
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: '{ id: '+id+', type: '+type+' }',
contentType: 'application/json',
dataType: 'json',
success: function(data) {
dataObject = JSON.parse(data);
// process data
},
error: function(e) {
console.log(e.message);
}
});
You can use your existing PHP code with this solution. The url you point to would just have to print the JSON result, as you are currently doing in getparentids().

Categories