Ajax post request is not functioning - php

I don't understand why my ajax did not returning any value after post. I am displaying count of registered user in a html table and allowing admin to click each of the count to see list of user name.
My html displaying count of registered user :
$sql2 = "SELECT COUNT(*) AS count FROM reg WHERE reg_id = '".$row['reg_id']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<a class="slot" data-slotid='.$row['reg_id'].' href="">'.$row2['count'].'</a>';
}
}
$sql2 = NULL;
Ajax request :
$('.slot').on('click', function(){
var slotid = $(this).data('slotid');
$.ajax ({
type: 'POST',
url: 'my-domain.com/ajax-request',
data: { slotid : slotid },
success : function(htmlresponse) {
$('#user_list').html(htmlresponse);
console.log(htmlresponse);
}
});
});
My php function from another file to filter database row :
if(isset($_POST['slotid'])){
// Mysql SELECT statement and echo query result
}
If I place a alert(slotid) right after var slotid = $(this).data('slotid'); in the ajax function, it will display the correct value for each of the clicked link. But when I try to echo $_POST['slotid']; at php side, there is not value returned. It seems like the whole page is refreshing.

Related

Loop through a list of div using setInterval to refresh data every x seconds

I have this page that consists of a list of user posts / message. When a post is liked, I want it to reflect on all other users, and based on my research setInterval can get the job done by refreshing a specific content for a number of seconds. Currently, I'm having trouble looping through all the user messages and show the updated number of likes. What's happening is that the number displayed is constantly changing and looping through all the values for a single post. Example: If I have 1, 0, and 2 likes respectively on three different posts, the number for the first post changes to 1, 0, and 2 instead of just showing "1". I'm kind of a beginner when it comes to AJAX.
Here's my code:
Jquery / Ajax
function refreshPostLikes() {
setInterval(function() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
}, 1000);
}
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
PHP Query
<?php
require_once('../connection.php');
$postID = $_POST['postid'];
$likeCountQuery = "select count(*) as total_likes from posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while($likeNumber = mysqli_fetch_assoc($likeQueryResult)) {
$likes = $likeNumber['total_likes'];
if($likes != 0) {
echo $likes;
}
else {
echo '';
}
}
?>
Still not sure this is the best way to go, but the reason your code doesn't work is due to omitting the postid when updating the HTML in the success part of your code.
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
with this command $(".posts .like").html(data); //output number of likes
You are updating all the divs which have these classes specified with the same value.
Set postid as id for the div and change the command to
$("#postid").html(data); //output number of likes
is constantly changing and looping through all the values for a single
post
This happens because there is no reference to the post that needs to be updated. What you are doing now is to cycle through all the elements that have the ".posts .id" classes, therefore the update applies to all the posts and not the single one. You should modify your function to make it update only that post (try passing it a unique id in html)
Where N is the id of your post. (For example postid)
Then update the value using this
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {
postid: postid
}, //send data to php file
success: function(data) {
//$(".posts .like").html(data); //output number of likes
$("#post-"+postid).html(data); // in this way we're get the right post
}
});
}
function refreshPostLikes() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
setTimeout(refreshPostLikes, 1000); //Check every sec if there are update
}
setTimeout(updateChat, 1000); //Start the check
Prevent SQL Injection
Escape is not enough
<?php
require_once ('../connection.php');
$postID = $_POST['postid']; //Escape this value before use inside the query see linked question
// NEVER TRUST USER INPUT
//$likeCountQuery it could be used for perform a SQL Injection NEVER TRUST USER INPUT
//NEVER !!!
$likeCountQuery = "SELECT COUNT(*) AS total_likes FROM posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while ($likeNumber = mysqli_fetch_assoc($likeQueryResult))
{
$likes = $likeNumber['total_likes'];
if ($likes != 0)
{
echo $likes;
}
else
{
echo '';
}
}
?>

Initialize first ajax data with a preset value then pass it from success response

How can I initialize the lastID in jquery only first time with the value 0 because var lastID = 0; does not work.
I have this ajax script in index.php
<script>
$(document).ready(function () {
var lastID = 0;
function getData() {
$.ajax({
type: 'GET',
url: 'data.php',
data: {lastID: lastID},
dataType: 'json',
success: function (data) {
lastID = data[0].id;
console.log(lastID);
$.each(data, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.details)
).appendTo('#output');
});
}
});
}
getData();
setInterval(function () {
getData();
}, 10000); // it will refresh your data every 10 seconds
});
</script>
This is the url: 'data.php' :
$sql = "select * from oders where id > ".$lastID." ORDER BY id DESC";
...
echo json_encode($dataArray);
With this query I get 0 results, and in console (console.log(lastID);) I have no data.
If I change the query like this :
$sql = "select * from oders where id > 0 ORDER BY id DESC";
In console.log(lastID); I get the correct last id. And in html I get the correct data and every 10 seconds it keeps adding same results over and over again.
I can't figure out how to initialize lastID first time as 0 (or the last ID in the database), and on every 10 seconds refresh, take the last ID from the ajax success data.
Where does your $lastID variable come from, how is it defined?
It looks like you are not getting the correct value from the $_GET array.
What you should do to both solve that problem and the sql injection problem you have, is switch to a prepared statement:
$sql = "select * from oders where id > ? ORDER BY id DESC";
And bind $_GET['lastID'] to the placeholder before / during the execution of your query (depending on whether you are using mysqli or PDO).

Clear previous ajax response data before appending new data

I am trying to .append() a selected data from a radio button but it display all the previous respond result.
My HTML :
$sql = "SELECT DISTINCT(name) FROM table1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$i = 1;
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
$sql2 = "SELECT * FROM table1 WHERE list = '".$row['list']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<input name="group['.$i.']" class="id" type="radio" data-id="'.$row2['id'].'" />'.$row2['list'];
}
}
$sql2 = NULL;
$i++;
}
}
$sql = NULL;
My ajax to get data and append :
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
}
});
});
For PHP side if there is $_POST['id'] then do mysql query to filter from table and return result.
if(isset($_POST['id'])){
$sql = "SELECT * FROM table1 WHERE id = '".$_POST['id']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
}
}
}
So what happened in my ajax result box, it keep appending the previous data that been processed by ajax together with the new data.
EDIT : Example append result :
First result of selected radio button : string 1
Second result of selected radio button : string 2
So result should be :
string 1
string 2
Sorry there was a mistake with my explanation. My ajax box result is resulting something like this :
string 1
string 2 (new data from another selected radio)
string 2 (new data is duplicating)
If adding select another radio it will become like this :
string 1
string 2
string 2
string 3 (new data)
string 3 (new data duplicating)
string 3 (new data duplicating)
string 3 (new data duplicating)
My ajax box result :
<div id="list"></div>
Add any class in label and input
echo '<label class="ajax">'....
....
echo '<input class="ajax" ...
....
And Remove in each selection or change in ajax
$('.ajax').remove();
$('#list').append(data);
Or better
$('#list .ajax').remove();
$('#list').append(data);
Update
Or simple add div to your ajax response
$('#list').append("<div class='ajax'>"+data+"</div>");
and then use this code
$('#list .ajax').remove();
$('#list').append(data);
I think you jQuery looks ok. It would be possible for your SQL query to have multiple rows as a result. This could mean that your id value is actually returning two rows. They include the first row and the second row.
You should remove a previously-attached event handler from the elements to avoid multiple click.
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
$('.id').off('click'); // remove a previously-attached event handler from the element.
}
});
});

Php: Display something if First Record is Reached

I have a database where it has 10+ records:
Accid | Firstname | Lastname
1. John Marshall
2. Sherlock Holmes
3. Random Dude
...
I'd display this using echo on php but with AJAX... it first loads up 5 users, and when the user has scrolled at the bottom of the page, it will load another 5 on the list (it adds the Offset's value +=5). Here's my display code:
$sql = "SELECT * FROM users ORDER BY lastname DESC LIMIT 5 OFFSET 5";
$result = mysqli_query($connection,$sql);
While($row=mysqli_fetch_assoc) {
echo $row['lastname']." ".$row['firstname']."<br/>";
}
This list could be very long if I have 100 users let's say.
Whenever the user scrolls at the bottom, another 5 users pops up. Now, if I reached the end of the whole records in the USERS database, I'd like to display something like - "End of User List"
How can I achieve this?
Jquery Code
$.ajax({
type: "GET",
url: "getusers.php",
data: {
'offset': 4
},
success: function(data){
$('#displayusers').append(data);
}
});
I'd like to disagree with #PressingOnAlways answer.
You can just send back a different response from PHP and check it in javascript.
$sql = "SELECT * FROM users ORDER BY lastname DESC LIMIT 5 OFFSET 5";
$result = mysqli_query($connection,$sql);
if(mysqli_num_rows($result) == 0){
die("last");
}
While($row=mysqli_fetch_assoc) {
echo $row['lastname']." ".$row['firstname']."<br/>";
}
Now you can just check it in javascript:
if(response == "last"){
mydiv.append('This is the end');
}
Now, I would like to show you my way of doing things, which (imo) is a lot cleaner:
First, your ajax calls
We're going to make sure our data will be in json format automatically from now on:
$.ajax({
type: 'GET',
url: "getusers.php",
cache: false,
data: {'offset': 4},
dataType: "json"
}).done(function(json){
if(json.hasOwnProperty("last"){
//No more results
//do your thang;
return false;
}
if(getLength(json) < 5){
//Smaller then 5, must have hit the last. Do your thang;
return false;
}
//It came here, so it's all good. Go on
$('#displayusers').append(data);
});
Secondly: Your PHP side
It's never a good plan to echo html over AJAX. It's way more efficient (takes up less servertime + sends smaller amounts of data over the internet highway) than doing it in PHP.
$sql = "SELECT * FROM users ORDER BY lastname DESC LIMIT 5 OFFSET 5";
$result = mysqli_query($connection,$sql);
$lastResponse = array("last" => "last");
if(mysqli_num_rows($result) == 0){
//Always send back json or it'll give you an error
die(json_encode($lastResponse));
}
$return = array();
While($row=mysqli_fetch_assoc) {
$return[] = $row['lastname']." ".$row['firstname'];
}
echo json_encode($return);
Third: A js function to check the arrayLength
//Checks the length of a json object or array
//Returns false if length is 0 or unable to check it
function getLength(obj) {
if (typeof obj == 'undefined') {
return false;
}
var l = 0;
if (typeof obj == 'object') {
l = Object.keys(obj).length;
}
else {
l = obj.length;
}
return (l == 0 ? false : l);
}
The best place to implement this feature would be on the JS client side. Since your PHP script has no way of knowing if it is the end of the list or not, you need to do this on the client. The JS code should check if the results returned from your php script is less than 5, if so, the "End of User List" should be printed.

Make A Next Button For More More Data?

Hi dear friends,
I hope u are all fine.
I want to make a next button for getting more data from mysql database.
For example:
$sql = mysql_query("SELECT * FROM table LIMIT 0,7");
It get 7 rows.For next data code is that.
$sql = mysql_query("SELECT * FROM table LIMIT 7,7");
I can i do that using ajax.
As you can see in many website like facebook,When you click on comment it give a limited
comment and when you click on more comment it give more and so on.In this proccess you can see
that the other content of page does not change.It means it can use ajax and how can I do that in ajax.
Please help me.Thanks.
your ajax would be something like this
var numberOfdata = 0;
$('#button').click(function () {
$.ajax({
url: 'load.php',
data: {
'limit' : numberOfdata,
// other data ...
},
type : 'post',
// other parameters...
}).success(function (data) {
// adding data to your website
numberOfdata += 7;
});
});
and in your server side, you could do something like this
... other operations
mysql_query("SELECT * FROM table LIMIT " . $_POST['limit'] . ",7");
... continuting the work
Note: You should be able to handle SQL injections on your own.
Edit: please note that mysql_query is not recommended.
You have to send the current comments count via Ajax, get the new ones from the response and display them.
Javascript:
$(document).ready(function() {
$('a.pagination-more').click(function() {
var current_comments_count = $(this).data("current_comments_count");
$.ajax({
type: "POST",
url: "pagination/pagination_ajax_more.php",
data: { "limit_start":current_comments_count },
beforeSend: function() {
$('a.pagination-more').html('<img class="loading-gif" src="pagination/loading.gif" />');
},
success: function(html){
$("#more").remove(); // This is the "More" button. It is appended to the end again in the 'html' variable
$("ul#updates").append(html);
if($("a#end")[0]) {
$("div#more").remove();
}
}
});
return false;
});
});
On the PHP side you just get $limit_start, get results from the database and echo the html like:
$limit_start = $_POST['limit_start'];
$query = mysql_query("SELECT COUNT(*) FROM `table` LIMIT 0, $limit_start");
$current_comments_count = mysql_num_rows($query);
$query = mysql_query("SELECT * FROM `table` LIMIT $limit_start, 7");
while($row = mysql_fetch_assoc($query)) {
echo '<li>
blah blah...
</li>';
}
if(mysql_num_rows($query) == 7)
echo '<div id="more"><a data-current_comments_count="$current_comments_count" class="button pagination-more" href="#">More</a></div>';
else
echo '<div id="more"><a id="end" class="button pagination-more" href="#">The button will be removed from jQuery...</a></div>';
Of course it is strongly recommended to secure your application and not to use only mysql_query(). This code is working but I removed some other stuff and didn't test it now. So, some errors may occur.

Categories