jQuery ajax works in Chrome but not Firefox or IE - php

Fair warning: I am no expert, but I did manage to get this far. My code isn't beautiful and it is rough. It is a fairly complex system so don't be shy to ask questions.
So I have an annoying problem where my code works in chrome but nowhere else. It seems like none of my javascript is working in either Firefox or IE. PLEASE NOTE THAT EVERY TIME YOU SEE PHP INSIDE A DIV IT SIMPLY REPRESENTS THE # OF THE POST INSIDE THE DATABASE.
My code displays posts where each post is paired with a like and dislike button built with spans. There is a checkbox that shows/hides all liked posts and another that does the same for disliked posts when selected. When a user likes or dislikes a post by clicking the button, values are sent to my DB through ajax (to check.php) so they can be recalled on future visits.
Again, it all works fine in Chrome but not in IE and Firefox.
Also, unless I insert the values into my userPosts table in my database manually first, no new posts and values are saved in my DB. For example, if my DB already has values for posts 1-3, all future decisions by the user to like/dislike those posts are sent and saved no problem but if I add a new post (post4) and the user likes or dislikes it, no values get sent... it seems like the INSERT doesn't work in check.php whereas the UPDATE functions just fine.
Here is the jQuery that sits inside the loop, you should find it annotated to your satisfaction:
<script type="text/javascript">
$(document).ready(function() {
// Declare variables
var checked = <?php echo $row['value']; ?>; //get value of Liked or Disliked from database
var postID = <?php echo $row['postID']; ?>; //get post ID from database
var userID = <?php echo $current_user->ID; ?>; //get the wordpress user's ID
var showLikes = $("input[name*='show_likes']"); //represents checkbox for Hide Liked
var showDislikes = $("input[name*='show_dislikes']"); //represents checkbox for Hide Disliked
// Set the remembered Liked and Disliked buttons
if (checked == 1) {
$('#post_<?php echo $row['postID']; ?>').addClass('like');
$('#like_<?php echo $row['postID']; ?>').removeClass('likeimgoff').addClass('likeimgon');
} else if (checked == 0) {
$('#post_<?php echo $row['postID']; ?>').addClass('dislike');
$('#dislike_<?php echo $row['postID']; ?>').removeClass('dislikeimgoff').addClass('dislikeimgon');
}
//When Liked button is clicked do this
$('#like_<?php echo $row['postID']; ?>').click(function() {
// Declare variables
var value = '1';
// Send values to database
$.ajax({
url: 'check.php',
type: 'POST',
data: 'userID=' + userID + '&postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_<?php echo $row['postID']; ?>').html('').html(result).prependTo('#post_<?php echo $row['postID']; ?>');
}
});
// If post is Disliked, change to Liked
$('#post_<?php echo $row['postID']; ?>').removeClass('dislike').addClass('like');
$('#dislike_<?php echo $row['postID']; ?>').removeClass('dislikeimgon').addClass('dislikeimgoff');
$('#like_<?php echo $row['postID']; ?>').removeClass('likeimgoff').addClass('likeimgon');
// If Hide Liked checkbox is on, toggle the post
if (showLikes.attr('checked')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
return false;
});
//When Disliked button is clicked do this
$('#dislike_<?php echo $row['postID']; ?>').click(function() {
// Declare variables
var value = '0';
// Send values to database
$.ajax({
url: 'check.php',
type: 'POST',
data: 'userID=' + userID + '&postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_<?php echo $row['postID']; ?>').html('').html(result).prependTo('#post_<?php echo $row['postID']; ?>');
}
});
// If post is Liked, change to Disliked
$('#post_<?php echo $row['postID']; ?>').removeClass('like').addClass('dislike');
$('#like_<?php echo $row['postID']; ?>').removeClass('likeimgon').addClass('likeimgoff');
$('#dislike_<?php echo $row['postID']; ?>').removeClass('dislikeimgoff').addClass('dislikeimgon');
// If Hide Disliked checkbox is on, toggle the post
if (showDislikes.attr('checked')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
return false;
});
//When Hide Liked checkbox clicked, toggle all Liked posts.
$("input[name*='show_likes']").click(function() {
if ($('#post_<?php echo $row['postID']; ?>').is('.like')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
});
//When Hide Disliked checkbox clicked, toggle all Disliked posts.
$("input[name*='show_dislikes']").click(function() {
if ($('#post_<?php echo $row['postID']; ?>').is('.dislike')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
});
});
</script>
Here is the code for each post, also sitting in the loop followed by the #Message that appears when the ajax returns the output of check.php and finally closes the loop:
<div id="post_<?php echo $row['postID']; ?>" class="post">
<div id="post_<?php echo $row['postID']; ?>_inside" class="inside">
<div id="like">
<a id="like_<?php echo $row['postID']; ?>" class="likeimgoff" href="#"><span></span></a>
</div>
<div id="dislike">
<a id="dislike_<?php echo $row['postID']; ?>" class="dislikeimgoff" href="#"><span></span></a>
</div>
<b><?php echo $row['Title']; ?></b><br>
<?php echo $row['Description']; ?><br>
</div>
</div>
<div id="Message_<?php echo $row['postID']; ?>" class="reminder"></div>
<?php
}
?>
</div>
Here is check.php:
<?php
mysql_connect("name.database.com", "username", "password") or die(mysql_error());
mysql_select_db("databasename") or die(mysql_error());
if (isset($_POST['userID'])){
$userID = mysql_real_escape_string($_POST['userID']);
}else{
echo "No userID";
}
if (isset($_POST['postID'])){
$postID = mysql_real_escape_string($_POST['postID']);
}else{
echo "No postID";
}
if (isset($_POST['value'])){
$value = mysql_real_escape_string($_POST['value']);
}else{
echo "No value";
}
$query = mysql_query("SELECT * FROM userPosts WHERE userID='$userID' AND postID='$postID';") or die(mysql_error());
if (mysql_num_rows($query) > 0) {
mysql_query("UPDATE userPosts SET value='$value' WHERE userID='$userID' AND postID='$postID';") or die(mysql_error());
} else {
mysql_query("INSERT INTO userPosts (userID, postID, value) VALUES ('$userID', '$postID', '$value') ") or die(mysql_error());
}
echo "UserID: " .$userID. " PostID: " .$postID. " Value: " .$value;
?>
So there you have it. I know it is a lot of code, so please don't shy away and feel free to ask questions!

Sorry, I didn't took the time to read your whole post but usually this type of problems are of a javascript error. If you don't have it, install Firebug on Firefox and see in the firebug console if you have any errors, also look if the ajax call is made and what answer you get.

Related

What is return false in jquery and attr + ajax

First let me show you the code
This is the script
var user_id = $(this).attr("id");
var datastring = 'user_two='+ user_id;
$(".follow").click(function(){
$.ajax({
type: "POST",
url: "include.php",
data: datastring,
success: function(html){}
});
$("#follow"+user_id).hide();
$("#unfollow"+user_id).show();
return false;
});
Here is php
<?php
$query = $handler->query("SELECT * FROM users");
while ($row = $query->fetch()) {
$user_two = $row['id'];
$user_one = 1;
?>
<p><?php echo $row['username'];?></p>
<?php
$follow_check = $handler->query("SELECT * FROM follow WHERE user_one='$user_one' AND user_two='$user_two'");
if ($follow_check->rowCount() == 0) {?>
<div id="follow<?php echo $user_one;?>">
Follow
</div>
<div id="unfollow<?php echo $user_one;?>" style='display:none'>
Following
</div>
<?php }else{?>
<div id="follow<?php echo $user_one;?>" style='display:none'>
Follow
</div>
<div id="unfollow<?php echo $user_one;?>" >
Following
</div>
<?php } ?>
<?php } ?>
Here is the php for Insert query
<?php
include('db.php');
$user_two = $_POST['user_two'];
$query = $handler->query("INSERT INTO follow (user_one,user_two) VALUES ('1','$user_two')");
?>
there two things i need to insert which is user_one = Session=0 or the current logged in user but i just made it static for the mean time and the user_two which is the users id or the one you will click to follow that person. But idk how to do it in ajax, like in php you can get the value of the link like <a href="?id="> and then to get the value, $_GET['id'] but idk how to store that value to script
I just need an explanation on user_id = $(this).attr("id");
and the return false inside the $(".follow").click and when I make it to false i need to refresh the page just to see the changes of links to follow and following why is it like that?
By the way, When i click the follow link it will successfuly insert to the database but the user_two's value is always 0 because I dont know how to store link id to the script.
Not 100% sure if i understood but let me try:
First: id="<?php echo $user_id; ?>" it's ok.
You can get it with var user_id = $(this).attr("id");
Maybe you should move this line inside the $(".follow")... block
$(".follow").click(function() {
var user_id = $(this).attr("id"); //"this" will refer the element with the "follow" class. Then user_id will be the value of the id for the clicked element.
$.ajax({
type: "POST",
url: "include.php",
data: {user_two: user_id}
}).done(function(data) {
data = JSON.parse(data);
if(data.msg) {
//everything is ok
$("#follow"+user_id).hide();
$("#unfollow"+user_id).show();
} else {
//handle the error
}
)}
});
PHP part:
<?php
include('db.php');
$user_two = $_POST['user_two'];
$query = $handler->query("INSERT INTO follow (user_one,user_two) VALUES ('1','$user_two')");
if($query) { //check if query ran successfully
echo json_encode(array("msg" => 1)); 1 for success
} else {
echo json_encode(array("msg" => 2)); 2 for error
}
?>
As for the "what is return false in ajax":
.follow -> targets an tag. Clicking on an a tag makes your browser navigate to the url specified in href="". return false disables this behaviour as you don't need the page to refresh or go to another page :)

Deleting an image only after the form is submitted

After a picture is uploaded I want to let the user have the option to delete it by clicking on the 'x' on the image. I tried some jquery codes that I searched online but nothing had the result I want. Is there a way to remove the image from the database only when the submit button is clicked rather than redirecting to a delete page and then having to go back to delete another image?
if($res18 && mysql_num_rows($res18) > 0){
while($row18 = mysql_fetch_assoc($res18)){
if (file_exists($row18['images']) === true){ ?>
<?php
//mysql_query("DELETE FROM `images` WHERE `images`='".$row18['images']."' AND `ad_id` = '".$id."'");
echo '<img src="'.$row18['id'].'" class="pictures">';
}
}
}
insert quesry:
mysql_query("INSERT INTO `images` ($fields) VALUES ($data)");
I assume the logic would be somewhat like this: Once the 'x' link is clicked, run a function that runs the delete query.
Any help is appreciated!
UPDATE:
$res18 = mysql_query("SELECT * FROM `images` WHERE `ad_id` = '" . $id . "'");
if($res18 && mysql_num_rows($res18) > 0){
while($row18 = mysql_fetch_assoc($res18)){
$picture = $row18['images'];
$pic_id = $row18['id'];
if (file_exists($picture) === true){ ?>
<img src="<?php echo $picture ?>" id="img-<?php echo $picture ?>" class="pictures">
<?php
}
}
}
<script type="text/javascript">
$(document).ready(function(){
// set onclick for all 'a' elements having the 'addition_image_close' class
$('a.addition_images_close').click(function() {
var $pic_id = $(this).prop('data-id');
var $picture = $(this).prop('data-id');
// post to delete.php, sending id=$picture as data and setting success handler
$.post('delete.php', {id: $picture}, function() {
// remove elements from page
$('#img-' + $picture).remove();
$('#a-' + $pic_id).remove();
});
});
});
</script>
and the delete.php has the following:
$id = $_GET['id'];
mysql_query("DELETE FROM `images` WHERE `ad_id` = '".$id."'");
a list.php could be something like this:
<?php
// ...
// render list
if($res18 && mysql_num_rows($res18) > 0) {
while($row18 = mysql_fetch_assoc($res18)) {
if (file_exists($row18['images']) === true){ ?>
<a href="javascript:return(0);"
class="addition_images_close"
data-id=<?php echo $row18['id'] ?>
id="a-<?php echo $row18['id'] ?>"
>X</a>
<img src="<?php echo $row18['id'] ?>"
id="img-<?php echo $row18['id'] ?>"
class="pictures">
}
}
}
?>
<!-- add actions on the links rendered above -->
<script type="text/javascript">
// do this when page is loaded
$(document).ready(function(){
// set onclick for all 'a' elements ahving the 'addition_image_close' class
$('a.addition_image_close').click(function() {
var $id = $(this).prop('data-id');
// post to delete.php, sending id=$id as data and setting success handler
$.post('delete.php', {id: $id}, function() {
// remove elements from page
$('#img-' + $id).remove();
$('#a-' + $id).remove();
});
});
});
with a delete.php receiving an id parameter and performing the delete query

Voting system with jQuery, Ajax and PHP works only local server

I am a no good in PHP (just learning).
I tried modifying a php voting script which I downloaded from a free source. i can add image though (it was not an easy task for me and I am not done yet).
Now Voting works fine on my local server , but online it doesn't. If I click to vote, the numbers just disappear without return. below are the codes to look into.
index.php ---
<?php include('config.php');
$sql=mysql_query("SELECT * FROM messages ORDER BY `messages`.`up` DESC LIMIT 20");
while($row=mysql_fetch_array($sql)) { $title=$row['title']; $desc=$row['desc'];
$mes_id=$row['mes_id']; $image=$row['image']; $up=$row['up'];
$down=$row['down']; ?> <div id="vote"> <div class="box1">
<div class='up'><a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?></a></div>
<div class='down'><a href="" class="vote" id="<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?></a></div></div>
<div class='image' ><?php echo "<img src=user/admin/".$image ." width='87%' height='70%'/>"?></div>
<div class ='title'><?php echo $title; ?></div>
<div class='box2' >
<?php echo $desc; ?> </div> </div>
<?php } ?>
up_vote.php --------------------------
<?php include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id']) { $id=$_POST['id']; $id = mysql_real_escape_String($id); $ip_sql=mysql_query("SELECT ip_add FROM voting_ip WHERE mes_id_fk='$id' AND ip_add='$ip'");
$count=mysql_num_rows($ip_sql)or die(mysql_error());
if($count<=20)
{
$sql = "UPDATE messages SET up=up+1 WHERE mes_id='$id'"; mysql_query( $up);
$sql_in = "INSERT INTO messages (mes_id_fk,ip_add) VALUES ('$id','$ip')"; mysql_query( $sql_in);
} else
{ echo "<script>alert('You have already voted');</script>"; }
$result=mysql_query("SELECT up FROM messages WHERE mes_id='$id'");
$row=mysql_fetch_array($result); $up_value=$row['up']; echo $up_value; } ?>
down_vote.php -----------------------------
<?php include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id']) { $id=$_POST['id'];
$id = mysql_real_escape_String($id);
$ip_sql=mysql_query("SELECT ip_add FROM voting_ip WHERE mes_id_fk='$id' AND ip_add='$ip'");
$count=mysql_num_rows($ip_sql) or die(mysql_error());
if($count<=0)
{ $sql = "UPDATE Messages SET down=down+1 WHERE mes_id='$id'"; mysql_query( $sql);
$sql_in = "INSERT INTO voting_ip (mes_id_fk,ip_add) values ('$id','$ip')"; mysql_query( $sql_in);
} else { echo "<script>alert('You have already voted');</script>"; }
$result=mysql_query("SELECT down FROM Messages WHERE mes_id='$id'");
$row=mysql_fetch_array($result);
$down_value=$row['down']; echo $down_value; }
?>
Javascript --------------------------- (this is at the index header with some HTML codes)
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('<img src="dot.gif" align="absmiddle">');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
} });
}
else
{
$(this).fadeIn(200).html('<img src="dot.gif" align="absmiddle">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
I appreciate anyone helping out, thanks everyone.
From your code,
if($count==50)
then only the values are being updated!!. How is it possible for a person who is going to vote for the first time???
It should be
if($count<50)
Going to take a wild stab here but 9/10 'It works locally but not on live' issues are either php version mismatches or differences in Apache config (differing module configurations etc) presuming LAMP.
Check the php versions match and if they don't check the change logs to detect any functions that do not work within both. This is likely the issue.
And as commented above. Always check your server logs.

How to get database retrieved value in jquery?

I want to update a likes on database when a user clicks on "like"(same as facebook like). I will load various posts from database. For each posts there is a unique field on database called mid(message Id) and when user clicks "like" below the post i want to increment likes on database for that specific message(it can be through mid). I want to implement this function using jquery because if i pass mid through url it will navigate to that page and get loaded whole page so i need to done it behind the page through AJAX call. Let me show a model how my database retrieval is
$cot = "select * from posts where userid = $usr LIMIT 10";
$ex = mysql_query($cot, $con);
while($cont = mysql_fetch_array($ex))
{
$date = date_create($cont['date']);
$mid = $cont['mid'];
echo "<div id='posts'>";
echo $cont['message'];
echo $photo;
echo "<div class='like'>"; //echo $mid; /* It is to show message id*/
echo "<a href='#'>Like</a></div>"; //When Clicked Like i Want to increment likes on DB
echo "Likes(" . $cont['Likes'] . ")";
echo date_format($date, 'd-m-Y H:i:s');
echo "<hr>";
echo "</div>";
}
i want this to be done over jquery and ajax call. I just need jquery code to call php file increment.php and pass mid(message Id) to that page.
maybe you need something like this:
echo "<a href='javascript:void(0);' class='like' data-mid='".$cont['mid']."'>Like</a></div>"; //When Clicked Like i Want to increment likes on DB
Now this is the script:
<script type="text/javascript">
$(function(){
$(".like").live('click', function(){
$.ajax({
url : 'increment.php',
data : {'mid':$(this).data('mid')},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
}
},
error : function(resp){
alert("some error occured !");
}
});
});
});
</script>
On your increment.php:
<?php
$id = $_POST['mid'];
$sql = "update posts set Likes = Likes+1 where mid = '".$id."'";
//execute the above and return some thing
return 1;
?>
$.post('/increment.php', { mid: whatever });
With your example click handler, it's simple to add this in....
$(document).ready(function() {
$("div.pray").click(function() {
var mid=$(this).val();
alert(mid);
$.post('/increment.php', { mid: mid });
});
});

Print like count without page refresh

I have a like/unlike post on my website, and when I click the like button I would like the value of check2 to show beside like without me having to refresh the page to see it. Currently I'll click like and it inserts the data but only shows on a page refresh. I'm hopeless with this kind of stuff.
Here is the code in the order it executes.
Thanks for any help.
POST LIKE
echo "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
if($checklikes>0){
echo "Unlike";
}else{
echo "Like";
}
echo "</a> ";
$check2 = user_core::print_like_count($streamitem_data['streamitem_id']);
if($check2>0){
echo "(".$check2.")";
}
Ajax Function
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
if(obj.innerHTML=="Like"){
obj.innerHTML="Unlike";
}else{
obj.innerHTML="Like";
}
$.post("../include/like_do.php", { streamitem_id: postid} );
}
LIKE_DO
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
if($check==0){
?>
<?php
}else{
?>
<?php
}
}
else{
echo "<script>alert('Error liking post');</script>";
}
?>
USER_CORE
function check_liked($id,$streamid,$value){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_userid=$id AND feedback_rating=$value";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
return $check2;
}
function print_like_count($streamid){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_rating=1";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
if($check2>0){
echo "(".$check2.")";
}
}
What you're looking for is an AJAX submission using DHTML to change the value of the likes.
<script language="javascript">
$(".likeButton").click(function() {
$.post("likeProcessor.php", {
id: $(this).attr('id')
}, function(data) {
$("#likeIndicator" + $(this).attr('id')).html(data);
});
</script>
Then your likeProcessor script will simply return the number of likes for that item.
NOTE: This is pseudo-code to give you an idea of what needs to happen. For further info on jQuery and Ajax, RTM at http://www.w3schools.com/jquery/default.asp and http://www.w3schools.com/ajax/default.asp respectively.

Categories