Facing on Make Like Unlike Button in php , mysql using ajax calling - javascript

I m creating like and unlike button for my website , at my local server i used seprate file it it working fine but when i install at my website then it is not working properly.
I m Fetching some information using this code from url bar
<?php
error_reporting (0);
include "includes/session.php";
include 'database/db.php';
extract($_REQUEST);
if(isset($_GET["i"]))
{
$pid=($_GET['p']);
$lid=($_GET['i']);
}
?>
<?php
$likquery = mysql_query("select * from likes where userid=$id and postid=$lid");
if(mysql_num_rows($likquery)==1){
?>
<a class="unlike" id="<?php echo $lid ?>">UnLike</a> <span class="like_update" id="<?php echo $lid ?>"></span>
<?php }else{?>
<a class="like" id="<?php echo $lid ?>">Like</a>
<?php
}?>
AFTER this I use script
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('body').on('click','.like',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$('body').on('click','.unlike',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
And I m not getting any response but when i use
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".like").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$(".unlike").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
only once it is changing the value

Ok, the second version works only once, because at the beginning, the event is on the button, then you re-render the button by changing it's class and text, so the events get unbinded.
Same is for the 1st version. Jquery says: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().... If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
So re-bind the events after changing the button.
I suggest something like this:
function bindEvents() {
$('.like').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
//rebind events here
bindEvents();
}
});
$('.unlike').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
//rebind events here
bindEvents();
}
});
}
$(document).ready(function(){
bindEvents();
});
Also notice that in var postData = 'postid='+postId+'&uid=<?php echo $id ?>'; code, the php part won't be treated as php. It will be just a string. So replace that part with the following, assuming that the code is located inside a php file:
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;

Related

ajax post to php a null variable

I have a script that copies an entire div into a variable. It works when I alert the data, but It wont work when I try to echo it in php.
<script>
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php?id='+vin,
data: {ordering:orderIm},
dataType: 'html'
})};
</script>
And my php:
<?php
echo $_GET['id'];
echo '<br />';
echo gettype($_POST['ordering']);
echo $_POST['ordering'];
?>
Output:
JS2YB417785105302
NULL
You can using full post request
<script>
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php,
data: {ordering:orderIm,id:vin}, // added id:vin on POST parameter
dataType: 'html'
})};
</script>
And my php :
<?php
echo $_POST['id']; // converted into $_POST
echo '<br />';
echo gettype($_POST['ordering']);
echo $_POST['ordering'];
?>
when i use the succes function :
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php',
data: {ordering:orderIm,id:vin},
dataType: 'html',
success: function(data) {
alert(data)}
})};
it shows the correct data. i guess it means that its solved. i just dont see it in the php file while i access it via the console log--> double clicking on XHR finished loading.
even tho the variables types shows NULL in the php script, i can still manipulate the content of them and everything is working fine !

Setting a session variable in PHP using AJAX

After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.

JS Toggle Class

I am stuck on this. I have an ajax function posting to php. The post function is working fine. I just want css to toggle on and off with each click while posting with each click.
When I click the '.fav-btn' button the first time I want 'fav-h' to be added to the class for styling. Also post to the php script.
When I click the '.fav-btn' button the second time I want 'fav-h' to be removed and button returns to original style. Also post again to the php script.
I have tried various things including the .removeclass. My code is below, I am not sure how to get the fav-h class style to be removed on the second click.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).addClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn fav-h').click(function(){
$('.fav-btn fav-h').removeClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
Use $.toggleClass() to just have one block of code:
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).toggleClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){}
});
});
});
PS: your code was not working because you used $('.fav-btn fav-h'):
<div class="fav-btn">
<fav-h></fav-h> <!-- This is what this selector leads to -->
</div>
instead of the correct selector $('.fav-btn.fav-h'):
<div class="fav-btn fav-h"></div> <!-- Found the right one! -->
It looks like it is the same ajax call either way. You can probably just bind to the button once. Also, you might want to only update the class if the post was successful.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').on('click', function(){
var $t = $(this);
$t.addClass('fav-saving');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
$t.toggleClass('fav-h');
},
complete: function(){
$t.removeClass('fav-saving');
}
});
});
});

Deletinq record from database using ajax

I have problem with deleting records from database, using ajax and jquery. If i click to button nothing happens. there is my css:
<button class='delete_p' id_p='<?php echo $post_id; ?>'>x</button>"
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script src="delete_post.js"></script>
and there is ajax that i'm using:
$(document).ready(function(){
$('.delete_p').click(function(){
var del_id = $(this).attr('id_p');
$.ajax({
type:'POST',
url:'delete_post.php',
data:'delete_id='+del_id,
});
});
});
and there is delete_post.php that i'm using:
<?php
include 'esas/core/database/connect.php';
$id = $_POST['delete_id'];
$query = "DELETE FROM `status` WHERE `id` = '$id'";
?>
data shouldn't be a string but a JavaScript object:
$.ajax({
type: 'POST',
url: 'delete_post.php',
data: {
delete_id: del_id
}
});

How to pass variables from PHP to Javascript using Ajax calls

I read this post and assumed the technique in the answer would work with ajax calls. I have my ajax and php code below but it does not work.The client does not recognize the 'passed' variable. I do not know why nor how to remedy this.
Javascript
var irrelevant = 'irrelevant';
$('body').click(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: {mydata: irrelevant},
success: function(){
console.log('worky');
alert(myvar); // NOT worky!
}
});
});
PHP File
<?php
$thing = 10;
?>
<script>
var myvar = "<?php echo $thing; ?>";
</script>
try this in your ajax.success
success: function(data){
console.log('worky');
alert(data); // It should now, worky!
}
and in you php
<?php
echo 10;
?>
try this
in php
<?php $thing = 10; ?>
<script>
var myvar = "<?php echo $thing; ?>";
</script>
javascript
$('body').click(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: {mydata: irrelevant},
success: function(data){
$("#hiddendiv").html(data);
alert(myvar);
}
});
});

Categories