Why my Ajax/php request is executed twice? - php

well, i've an like/unlike script.
When i click on like or unlike, the php request is executed twice.
I've tried several things but i don't understand why.
Here my php request.
$query = "SELECT * FROM like_unlike WHERE postid=".$postid." and userid=".$userid;
$req = $bdd->prepare($query);
$req->execute();
$array = $req->fetchALL();
$count = count($array);
if($count == 0){
$insertquery = "INSERT INTO like_unlike(userid,postid,type)
values(".$userid.",".$postid.",".$type.")";
$insertquery = $bdd->prepare($insertquery);
$insertquery->execute();
and here my js file
$(document).ready(function(){
// like and unlike click
$(".like, .unlike").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 0;
if(text == "like"){
type = 1;
}else{
type = 0;
}
// AJAX Request
$.ajax({
url: 'likeunlike.php',
type: 'post',
data: {postid:postid,type:type},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var unlikes = data['unlikes'];
var difflikes = data['likes'] - data['unlikes'];
$("#likes_"+postid).text(likes); // setting likes
$("#unlikes_"+postid).text(unlikes);
$("#difflikes_"+postid).text(difflikes); // setting unlikes
}
});
});
HTML:
<img src="<?= $chemin ?>img/up.png" value="Like" id="<?php echo $id_vote_like; ?>"
class="img_vote_up zoom <?= $class_vote_like ?> " style="" /> <?= $log_e ?>
<span id="difflikes_<?php echo $postid; ?>" class="nb_votes"><?php echo $likes_d; ?>
</span>
<?= $log_i ?>
<img src="<?= $chemin ?>img/down.png" value="Unlike" id="<?php echo
$id_vote_unlike; ?>" class="<?= $class_vote_unlike ?> img_vote_down zoom" style=""
/> <?= $log_e ?>
Anyone has an idea ?

Related

Ajax not loading posts on live server but working on localhost

I'm trying to load posts of users from my database to the website but the ajax part isn't loading for some reason. It was working on localhost but not working on the live server. Is there some problem in the ajax code or the code written in the index page?
Here in the index page the posts_area div part isn't loading
index.php
<?php
include("includes/header.php");
if(isset($_POST['post'])){
$post = new Post($con, $userLoggedIn);
$post->submitPost($_POST['post_text'], 'none');
}
?>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Got something to say?"></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<div class="user_details column">
<h4>Popular</h4>
<div class="trends">
<?php
$query = mysqli_query($con, "SELECT * FROM trends ORDER BY hits DESC LIMIT 9");
foreach ($query as $row) {
$word = $row['title'];
$word_dot = strlen($word) >= 14 ? "..." : "";
$trimmed_word = str_split($word, 14);
$trimmed_word = $trimmed_word[0];
echo "<div style'padding: 1px'>";
echo $trimmed_word . $word_dot;
echo "<br></div><br>";
}
?>
</div>
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "https://bestconnect.000webhostapp.com/includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') {
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
</div>
ajax_load_posts.php
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['posts'])) {
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
<?php
header("Access-Control-Allow-Origin: *");
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['userLoggedIn']))
{
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>

Comments show in last post in codeigniter

Check my image all comment show in one post i am pass post_id 53 56 here is 53 comment and 56 comment you see but it show 53 comment in 56 post i have post and comments system like facebook but my problem is that all comments show in last post. please check it my code i have try many method but it's not working if you have any good solution soo please help me
Controller
public function commentlist(){
$conn = mysqli_connect("localhost","root","","finance");
$memberId = 1;
$sql = "SELECT * FROM tbl_comment INNER JOIN signup ON tbl_comment.u_id = signup.id";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
}
public function commentadd(){
$conn = mysqli_connect("localhost","root","","finance");
$u_id = $this->session->userdata('log_in')['id'];
$u_image = $this->session->userdata('log_in')['image'];
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$postID = isset($_POST['tmp']) ? $_POST['tmp'] : "";
$name = array();
$name[0] = $this->session->userdata('log_in')['f_name'];
$name[1] = $this->session->userdata('log_in')['l_name'];
$commentSenderName = implode(" ", $name);
$sql = "INSERT INTO tbl_comment(post_id, parent_comment_id,u_id,u_image,comment,comment_sender_name,date) VALUES ('" . $postID . "','" . $commentId . "','" . $u_id . "','" . $u_image . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
}
this is my view file
View
<form id="frm-comment_<?php echo $id;?>">
<div class="input-row_<?php echo $id;?>">
<?php if($this->session->userdata('log_in')['image'] !=NULL ): ?>
<img src="<?php echo base_url(); ?>uploads/<?php echo $this->session->userdata('log_in')['image'];?>" style="height:42px; width:42px;" class="img-circle">
<?php else : ?><img src="<?php echo base_url('assets/images/generic-avatar.jpg'); ?>" style="height:42px; width:42px;" class="img-circle">
<?php endif; ?>
<input type="hidden" name="comment_id" id="commentId_<?php echo $id; ?>"/>
<input type="hidden" name="tmp" id="tmp" value="<?php echo $id;?>" />
<input class="input-field" type="text" name="comment" id="comment_<?php echo $id; ?>" placeholder="Write a Comment..">
</div>
<input type="button" class="btn-submit" id="submitButton_<?php echo $id;?>" value="Comment" >
<div id="comment-message_<?php echo $id;?>" style='display: none;'>Comments Added Successfully!</div>
<div class="output_<?php echo $id?>" ></div>
</form>
</div>
</div>
</div>
</div>
Script
<script>
$( "#com_<?php echo $id; ?>" ).click(function() {
$("#comment_<?php echo $id;?>").focus();
});
function postReply(commentId) {
$('#commentId_<?php echo $id; ?>').val(commentId);
$("#comment_<?php echo $id; ?>").focus();
}
$(document).ready(function () {
listComment();
});
$("#submitButton_<?php echo $id;?>").click(function () {
$("#comment-message_<?php echo $id;?>").css('display', 'none');
var str = $("#frm-comment_<?php echo $id;?>").serialize();
$.ajax({
url: "<?php echo base_url();?>finance/commentadd",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message_<?php echo $id;?>").css('display', 'inline-block');
$("#comment_<?php echo $id; ?>").val("");
$("#commentId_<?php echo $id; ?>").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
function listComment(){
$.post("<?php echo base_url();?>finance/commentlist",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
var post_id = data[i]['post_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{comments = " \ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\<div class='comment-text'>\ <span>" + data[i]['post_id'] + "</span><span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
<a class='btn-reply' style='font-size:14px;' onClick='postReply(" + commentId + ")'> Reply</a>\
<span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$(".output_<?php echo $id?>").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "\ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\
<div class='comment-text'> <span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
\ <span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
</script>
<?php }?>
I think your code is complex because there is not need to save user image ,name in comment table ,you need to use only comment id(auto increment) post id, user id , comment.
Yo get all comments for particular post you should fetch by post ir for that post.
Example :- when user click on particular post , suppose its post id is 1 then as click click on this you have to pass a request with this post id to comment table where query will match this post id in comment id if this condition true then redirect page to view with all comment and show them.
Controller
Query:- $this->model_name->function_name($id);
In model
$this->db->where('post_id', $id);
$this->db->get('comment_table')->result_array();
This query will fetch all comment for clicked post.

How to use jquery ajax to get one variable from a php file to another php file

I'm having trouble passing a variable in my a php file to another php file using jquery ajax. I don't know why it doesn't read it though because everytime I echo the variable it's undefined or just plain blank.
teams.php
<?php
// Display members from database
$connect = mysqli_connect('localhost', 'root', '', 'chansandbox');
if(isset($_POST['display'])){
$team = "SELECT * FROM team";
$resultTeam = mysqli_query($connect, $team);
?>
<ul class="teams">
<li><a id="teamheader">LIST OF TEAMS</a></li>
</ul>
<?php
while($arrayTeam = mysqli_fetch_array($resultTeam)){
$team_id = $arrayTeam['team_id'];
?>
<ul class="teams" name="teamId" value="<?php echo $team_id ?>">
<li><?php echo $arrayTeam['team_name']; ?>
<ul class="menu">
<li class="memberdivholder">
<div class="gradeview">
<h1 id='options'><i class="fa fa-cog"></i>
Options:
<button class="topbutton">Grade Team</button>
<button class="topbutton">View Team</button>
<button class="teamdelete">Delete Team</button>
</h1>
</div>
<?php
$member = "SELECT * FROM employee WHERE team_team_id = '$team_id' ORDER BY position_pos_id=17 desc";
$resultMember = mysqli_query($connect, $member);
while($arrayMember = mysqli_fetch_array($resultMember)){
?>
<div class="memberholder">
<h1 class="clearfix">
<?php
if($arrayMember['position_pos_id']==17){
echo "<i class='fa fa-star-o' aria-hidden='true'></i>";
}
?>
<?php echo $arrayMember['emp_fname'] . " " . $arrayMember['emp_lname']; ?>
<button class="viewprofile">View Profile</button>
</h1>
</div>
<?php
}
?>
</li>
</ul>
</li>
</ul>
<?php
}
exit();
mysqli_close($connect);
}
?>
script.js
$('.teams').on('click', '.teamdelete', function(){
var teamId = $(.teams).attr("value");
if(confirm("Are you sure?")){
$.ajax({
url: "http://localhost:81/chansandbox/wp-content/themes/Skeleton/teamdelete.php",
method: "POST",
type: "POST",
data: {
team_id: teamId
},
success: function(data)
{
alert(data);
eval(data);
}
});
}
});
teamdelete.php
<?php
$connect = mysqli_connect('localhost', 'root', '', 'chansandbox');
$team_id = $_POST['teamId'];
$update = "UPDATE employee SET team_team_id = NULL WHERE team_team_id = '$team_id'";
if(mysqli_query($connect, $update)){
echo "Employees Updated";
$deleteteam = "DELETE FROM team WHERE team_id = '$team_id'";
if(mysqli_query($connect, $deleteteam)){
echo "Team deleted '$team_id'";
}
else{
echo "Team not deleted";
}
}
else{
echo "Employees not updated";
}
mysqli_close($connect);
?>
As you can see I'm trying to get the value of the ul (class=teams) in the teams.php and passing it on to the js script file using ajax and var teamId = $(this).attr("value"); and passing it onto teamdelete.php but it doesn't seem to work. Any help would really be appreciated thank you.
because $('.teamdelete') has no attr value ..
in your html you should put
<button class="teamdelete" value="<?php echo $arrayTeam['team_id']; ?>">Delete Team</button>
and in your javascript do this
var teamId = $(this).attr("value");
and in your php .. since the name of the post data = team_id you should do
$team_id = $_POST['team_id'];
Your data variable is incorrect...
The ajax data is sent as data: { NAME : VALUE }. The PHP is essentially calling $_POST['VALUE'] So the php doesn't know what that value is.
The PHP calls:
$_POST['teamId'];
But the ajax sends
team_id:
Try changing the PHP on teamdelete.php to:
$team_id = $_POST['team_id'];
There are additional issues as well...
html:
<button class="teamdelete" value="<?php echo $arrayTeam['team_id']; ?>" >Delete Team</button>
js:
$('.teams').on('click', '.teamdelete', function(){
var teamId = $(this).attr("value"); // ------------ CHANGED
console.log(teamId); // ----------- CHANGED should show the right ID in console
if(confirm("Are you sure?")){
$.ajax({
url: ".....teamdelete.php",
method: "POST",
type: "POST",
data: {
team_id: teamId
},
success: function(data)
{
alert(data);
eval(data);
}
});
}
});
PHP:
<?php
$connect = mysqli_connect('localhost', 'root', '', 'chansandbox');
$team_id = $_POST['team_id']; // ----------- CHANGED
$update = "UPDATE employee SET team_team_id = NULL WHERE team_team_id = '$team_id'";
if(mysqli_query($connect, $update)){
echo "Employees Updated";
$deleteteam = "DELETE FROM team WHERE team_id = '$team_id'";
if(mysqli_query($connect, $deleteteam)){
echo "Team deleted '$team_id'";
}
else{
echo "Team not deleted";
}
}
else{
echo "Employees not updated";
}
mysqli_close($connect);
?>
You can use the developers panel and inspector to confirm that the delete button has the correct value for the team.

Append content to div via jquery

My project is a kind of blog, with posts and comments area. I'm trying to make it async with jquery ajax. My problem is that when a new comment gets inserted asynchronously it appears in the div twice, and all the other comments disappear. If i refresh the page it looks fine.
VIEW:
<section id="comments_section_<?php echo $p1['post_id'];?>"> //THIS IS THE OUTPUT WHERE NEW COMMENTS WILL BE APPENDED
<?php
$data['comments'] = $this->model_mutamba->getComments($p1['post_id']);
if($data['comments'] != ""){ ?>
<div class="comments_container" id="comments_container_<?php echo $p1['post_id'];?>">
<?php foreach ($data['comments'] as $c){
$user_img3 = $this->model_mutamba->getUserPicId($c->aluno_id);
?>
<div>
<img style="height:32px;" src="<?php echo site_url();?>img/users/portfolio/<?php echo $user_img3;?>" alt="" class="align-left" />
<p>
<?php echo $this->model_mutamba->addSmilies($c->comment);?>
<br>
<span class="comments_date">
<?php
$c_date = explode('-', substr($c->comment_date,0,-8));
$date_num_word = monthNumToWords($c_date[1]);
echo substr($c->comment_date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0];?>
</span>
</p>
</div>
<?php } ?>
</div>
<?php } ?>
</section>
JS:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).html(response);
$(output).append(response);
}
});
}
}
CONTROLLER:
function insertNewComment(){
if($this->session->userdata('is_logged_in')){
$email= $this->session->userdata('email');
$comment= $this->FilterData($this->input->post('comment'));
$post_id= $this->FilterData($this->input->post('post_id'));
$this->load->model('model_mutamba');
if($this->model_mutamba->insertNewComment($email,$comment,$post_id)){
$this->load->model('model_user');
$count = $this->model_mutamba->countPostComments($post_id);
?>
<script>
var count = '<?php echo $count;?>';
var comments_count = '<?php echo "#comments_count_".$post_id;?>';
var content = "";
if(count == 1){
content = '<span class="comments_count">'+count+'</span> Comentário';
}else{
content = '<span class="comments_count">'+count+'</span> Comentários';
}
$(comments_count).html(content);
</script>
<?php
$this->load->model('model_user');
$user_img = $this->model_user->getUserPic($email);
echo '
<div>
<img style="height:32px;" src="'.site_url().'img/users/portfolio/'.$user_img.'" alt="" class="align-left" />
<p>
'.$this->model_mutamba->addSmilies($comment).'
<br>
<span class="comments_date">';
$date = date(date('Y-m-d H:i:s'));
$c_date = explode('-', substr($date,0,-8));
$date_num_word = monthNumToWords($date[1]);
echo substr($date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0].'
</span>
</p>
</div>';
}
}else{
redirect("inicio");
}
}
Will appreciate any help,
Thanks in advance
This is happening because in your AJAX success callback, you are adding response to the output TWICE - once with .html() and then again with .append().
.html(response) removes the previous HTML in your webpage, thats why you dont see other comments and it adds response to it.
With .append(response), it is adding response to the bottom of the div, that is the reason you are seeing the response twice!
Remove $(output).html(response) from the success callback and it will work fine.
So, your function needs to look like this:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).append(response);
}
});
}
}
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
//$(output).html(response); //Comment this line or the line below it.
$(output).append(response);
}
});
}
}
<div id="appenddiv">
<h1>append</h1>
</div>
<script type="text/javacript">
$("#appenddiv").append('<b>hello world</b>');
</script>

php variable for javascript ajax

I have a table that queries from a database that is updated frequently, and where
<span id="totalvotes1"></span>
and where
<span id="totalvotes2"></span>
I need to be able to be able to identify those in the line
success: function(data) { $('#totalvotes1').text(data); } });
in my ajax for each corresponding row queried... the way it is set up right now, my ajax will just display the information back into
<span id="totalvotes1"></span>
in the last row queried....
<?php
$sql = mysql_query("SELECT * FROM blogData ORDER BY id DESC");
$sql2=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 0 ORDER BY mes_id DESC");
$sql3=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 1 ORDER BY mes_id DESC");
$count_variable = 0;
while(($row = mysql_fetch_array($sql))AND($row2 = mysql_fetch_array($sql2))AND($row3 = mysql_fetch_array($sql3)) ){
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$category = $row['category'];
$podcast = $row['podcast'];
$datetime = $row['datetime'];
$message1=$row2['msg'];
$mes_id1=$row2['mes_id'];
$totalvotes1=$row2['totalvotes'];
$message2=$row3['msg'];
$mes_id2=$row3['mes_id'];
$totalvotes2=$row3['totalvotes'];
?>
<table class="content">
<tr>
<td>
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<span id="totalvotes1"><?php echo $totalvotes1; ?></span><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<span id="totalvotes2"><?php echo $totalvotes2; ?></span><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>
</td>
</tr>
</table>
<?php
}
?>
here is my general.js file
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(data) { $('#totalvotes1').text(data); }
});
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(data) { $('#totalvotes2').text(data); }
});
}
});
});
});
Possibly a earlier version of your latest question,
JSON encode, ajax and display back in html
In my answer on your latest question about this, I've given a detailed example of how to use JSON data between PHP and jQuery.

Categories