pass PHP value back to AJAX function on success - php

I'm building an AJAX timeline of wall posts and I have the following function to check for new posts and then post the new ones to the wall, similar to how Twitter works:
wall_posts.php
$news = tz::shared()->news->getNew(25);
<div id="wall_posts">
<?php foreach ($news as $news_post) { ?>
<div class="wall_post"><?php echo $news_post['message']; ?></div>
<?php } ?>
</div>
jQuery:
function checkForNewPosts() {
// This represents the last record in the table AKA the "most recent" news
var lastCustomerNewsID = <?php echo $news[0]['id']; ?>;
$.ajax({
url: "example.com/ajax.php",
method: "post",
data:{
lastCustomerNewsID: lastCustomerNewsID,
},
dataType:"text",
success:function(data)
{
$('#wall_posts').prepend(data);
}
});
}
setInterval(checkForNewPosts, 10000);
The news PHP array above with index 0 indicates it is the last/most recent ID in the array/table
PHP (ajax.php):
if ($_POST) {
$lastCustomerNewsID = $_POST['lastCustomerNewsID'];
$new_posts = tz::shared()->news->getNewForWall($lastCustomerNewsID);
$output = '';
if ($new_posts) {
foreach ($new_posts as $new_post) {
$output .= "<div class='wall_post'>";
$output .= $new_post['message'];
$output .= "</div>";
}
} else {
}
echo $output;
}
Note - The function getNewForWall pulls records with an id greater than the argument passed in
This works fine when getting a new post, however the problem is that I need to update the "last id" to the "newest id" from the new records returned in ajax.php each time the function runs, because currently once its grabs the newest posts the first time, its keeps recognizing those as new on an ongoing basis.
How can I pass the newest "last id" from the array in ajax.php back to the AJAX function each time it runs? Can I pass a separate variable back to the AJAX function?
Thanks!

First of all, I think PHP here should return JSON instead of HTML information
JQuery should process JSON to generate HTML information
The PHP code looks like this (this is an example)
<?php
$page = $_POST['page'];
$method = $_GET['method'];
if ($method == "list") {
$limit = 20;
$offset = ($page - 1) * $limit;
$post = new Post();
// Calculate offsets according to page limits and page numbers and query articles
//Let's assume that the field of content is "content"
$offset = ($page - 1) * $limit;
$post_list = $post->offset($offset)->limit($limit)->select();
$total = $post->offset($offset)->limit($limit)->count(); //Statistics of all entries
//Get the largest ID by ID sort
$last_id = $post->order('id desc')->find();
$last_id = $last_id['id'];
echo json_encode([
'last_id' => $last_id,
'post_list' => $post_list,
"maxpage"=>ceil($total / $limit), //Calculate the maximum number of pages
]);
} elseif ($method == 'last_check') {
$post = new Post();
//Get the largest ID by ID sort
$last_id = $post->order('id desc')->find();
$last_id = $last_id['id'];
echo json_encode([
'last_id' => $last_id,
]);
}
Now we can check whether there are new articles through timers and page flips.
And you can use maxpage to determine if there is the next page.
function checkForNewPosts() {
$.ajax({
url: "example.com/ajax.php?method=last_check",
method: "get",
dataType:"json",
success:function(data)
{
if(data.last_id>lastCustomerNewsID){
//Write a new post operation here.
lastCustomerNewsID = data.last_id;
}
}
});
}
function getNextPage(){
var html;
page = page + 1;
$.ajax({
url: "example.com/ajax.php?method=list",
method: "post",
data:{
"page": page
},
dataType:"json",
success:function(data)
{
//Collate JSON into the required HTML format
html = "";
$.each(data.post_list, function(i, item){
html = html + "<div class='wall_post'>" + item.contect + "</div>";
});
if(data.last_id>lastCustomerNewsID){
//Write a new post operation here.
lastCustomerNewsID = data.last_id;
}
if(data.maxpage<=page){
//If there is no next page
}
$('#wall_posts').prepend(data);
}
});
}
setInterval(checkForNewPosts, 10000);

Related

Creating Dynamic Pages with php and MySQL

I am creating a list of links in main.php using "donemler" table in mySQL database and would like to create a page that shows data from "sikkeler" table (which has a foreing key donemID that is used as a relationship between the two tables) as the user clicks it. (data.php is a part of the index.php which is a infinite scroll page)
Here I tried to call $row["donemID"] with GET method using
$k=$_GET['donemID'] in index.php but did not work.
I have also tried to use SESSIONS method where I add "$_SESSION['donemID']=$row$row["donemID"] to main.php
and called it back in index.php as
$k=$_SESSION['donemID']
but it also did not work.
I would like to learn how to create pages and show relevant data in php.
Thanks in advance!
main.php
<?php
require_once "config.php";
$sql = $conn->query("SELECT * FROM donemler ORDER BY donemID");
if ($sql->num_rows > 0) {
// output data of each row
while($row = $sql->fetch_assoc()) {
echo "<tr><td><a href='index.php?devletID=".$row["devletID"]."&donemID=".$row["donemID"]."'>" .$row["donemler"]. "</a></td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php
<script type="text/javascript">
var start = 0;
var limit = 20;
var reachedMax = false;
var dnmID = $_GET("donemID");
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() )
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'data.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit,
dnmID: dnmID,
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
data.php
<?php
if (isset($_POST['getData']) ) {
$conn = new mysqli('localhost', 'usrnm', 'pss', 'db');
$dnmID = $conn->real_escape_string($_POST['dnmID']);
$start = $conn->real_escape_string($_POST['start']);
$limit = $conn->real_escape_string($_POST['limit']);
$sql = $conn->query("SELECT * FROM sikkeler WHERE donemID='$dnmID' ORDER BY kayit_no DESC LIMIT $start, $limit");
if ($sql->num_rows > 0) {
$response = "";
while($data = $sql->fetch_array()) {
$response .= '
<tr>
<td>ICD#'.$data['kayit_no'].'</td>
<td>'.$data['donemi'].'</td>
<td><img src="coin_images/'.$data['resim'].'" border="2" width="200px" /></td>
<td>'.$data['darp'].'</td>
<td>'.$data['tarih'].'</td>
<td>'.$data['birim'].'</td>
<td>'.$data['agirlik'].'</td>
<td>'.$data['cap'].'</td>
<td>'.$data['tip'].'</td>
<td>'.$data['reference'].'</td>
</tr>
';
}
exit($response);
} else
exit('reachedMax');
}
?>
You are checking through two different request methods:
$_POST['getData']
$k=$_GET['donemID']
Since you are using the query strings, it is a GET method to check with.
There is no such variable i.e. getData on main.php

Continuously get PHP loop data in Ajax Call

I have this codes in process.php:
$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
$user_email = get_user_email($r); // Get email of each user
if (!empty($user_email)) {
send_w_mail(); // Send email to each user
$step++;
echo json_encode(
['step' => $step, 'all' => count($users)]
); // echo output
}
}
And this is my ajax call in index.php:
$("#send-message").click(function () {
$.ajax({
url: global_base_url + 'process.php', // global_base_url defined.
async : true,
type: 'POST',
data: {'users': input_users}, // input_users is val() of a input.
encoding: 'UTF-8',
success: function (data) {
data = $.trim(data);
if (data){
data = $.parseJSON(data);
var p_value = parseInt(data.step*100)/data.all;
set_progressbar_value(p_value); // set progressbar value. sample: 23%
}
}
});
});
This codes don't have any problem for execute and showing result.
But I want to Continuously get output json data from process.php in order to show process of each $step in Percent unit in a bootstrap process-bar;
I found some function like ignore_user_abort(), ob_clean() and ob_flush() but don't know how can I solve my problem with them.
How Can I do this? Please help me to solve the problem.
Thanks a lot.
There are two ways of approaching this problem
Websocket
Long polling
I will be describing the long polling method here:
$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
$user_email = get_user_email($r); // Get email of each user
if (!empty($user_email)) {
send_w_mail(); // Send email to each user
$step++;
echo json_encode(
['step' => $step, 'all' => count($users)]
); // echo output
//Flush the output to browser
flush();
ob_flush();
}
Jquery does not provide api for XMLHttpRequest.readyState == 3 (Loading docs here) so we need to use raw XMLHttpRequest object
$("#send-message").click(function () {
var prev_response = "";
var xhr = new XMLHttpRequest();
xhr.open("POST", global_base_url + 'process.php', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 3) {
// Partial content loaded. remove the previous response
var partial_response = xhr.responseText.replace(prev_response,"");
prev_response = xhr.responseText;
//parse the data and do your stuff
var data = $.parseJSON(partial_response);
var p_value = parseInt(data.step*100)/data.all;
set_progressbar_value(p_value);
}
else if(xhr.readyState == 4 && xhr.status == 200){
set_progressbar_value(100);
console.log("Completed");
}
}
xhr.send("users="+ input_users);
});

Adding icon to product added in cart PHP/Jquery

I am trying to add a checkmark to the products that have been added to cart.
I am using ajax to return.
But i know i am doing wrong.
I got a bit lost.
I made with php first,and it works,but only displays when i refresh the page.
My php code...
if(isset($_SESSION['product'][$id])){
$added='<a href="" class="badge-corner" product_id="'.$id.'" >
<span class="fa fa-check"></span></a>';
}else{
$added='';
}
I want to use ajax to display the checkmark.
This is where i get my product id and store them to session.
My add to cart function and item counter code..(cart_function2.php)
<?php header('Content-Type: application/json');
session_start();
if (isset($_GET['action'])) {
$action = $_GET['action'];
$prod = $_GET['prod_id'];
$result="";
switch ($action) {
case 'add':
$result = add_prod($prod);
break;
default:
$result = ['result'=>'error'];
break;
}
}
// Calculate subtotal here
$result['totals'] = new stdClass;
$total_in_cart=count($_SESSION['product']);
$_SESSION['products']=$total_in_cart;
if(isset($_SESSION['product'][$prod])){
$added='</span>';
}else{
$added='';
}
$result['added'] = $added;
$result['items'] = $total_in_cart;
echo json_encode($result);
function add_prod($prod){
//add function
$_SESSION['product'][$prod] = 1;
$_SESSION['products']++;
return ['result'=>'success'];
}
?>
And this is the script in my gallery...
$('.actions').click(function(e){
e.preventDefault(e);
var action = $(this).attr('data-action'); //gets button id
var id = $(this).attr('product_id');
console.log("triggered action " + action + " for product " + id);
$.ajax({
url: 'cart_functions2.php',
type : 'GET',
data: {action:action,prod_id:id},
dataType: 'json'
}).done(function(data) {
console.log("ajax call returned the following: " + JSON.stringify(data));
if (data.result == "success") {
$("#items").html(data.items);
$(".show").html(data.added) + id;
//some debugging script
i am trying to display in here
<div class="show">'.$added.'</div>
When i click add product, all my products gets checked at once.
Why?
Please help me,i'm still a noob at jquery.

Ajax, Update div with num_rows

I've built a notification system, and its almost working. I just have one niggly bit that I can't seem to get my head around.
When a new update comes in from a friend it prints out the number of new notifications as expected, only if a user posts twice num_rows 2 pops up.. but if a user posts again it updates and replaces the 2 new notifications number back to 1 in the div because I'm using html in the ajax to replace.
So my question is, how can I update the div to get the total amount of results so it goes 1,2,3,4 etc instead of 2,1,1,1,1.
I don't want to replace the num of new rows with only the (1) update in the div, just add to the amount of new updates already inside it.
A bit like when facebook shows amount of notifications. say I have two and a friends posts on my wall I then will have 3.. but at the moment its adding the last new num row and going back to 1.
AJAX
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
var notification_id= window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler;
if(response.num){
window.localStorage.setItem('lastId', response.notification_id);
var dataHandler = function(response){
var isDuplicate = false, storedData = window.localStorage.getItem ('lastId');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
if(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
}
}
}
});
}
setInterval(loadIt, 10000);
PHP
$json = array();
$com=mysqli_query($mysqli,"select notification_id,notification_content,notification_time from notifications where notification_id > '$id' AND notification_status=1 ");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num!=1){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
mysqli_free_result($com);
header('Content-Type: application/json');
echo json_encode($json);
}
The number of notifications on client-side is storedData.length.
So i would replace the counter
$("#mes").html(''+ response.num + '');
with
$("#mes").html(storedData.length);

jquery autcomplete returning source array

I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )

Categories