Php Ajax - Multiple calls in one page - php

Right now I have this code loading only 1 page (load.php?cid=1 but I want to load 5-8 (cid=1,cid=2,cid=3,cid=4,cid=5,cid=6,cid=10 ...etc )in different div(s).
how will I achieve it ?
$(document).ready(function() {
function loading_show() {
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loading_Paging').fadeOut 'fast');
}
function loadData(page) {
loading_show();
$.ajax({
type: "POST",
url: "load.php?cid=1",
data: "page=" + page,
success: function(msg) {
$("#container_Paging").ajaxComplete(function(event, request, settings) {
loading_hide();
$("#container_Paging").html(msg);
});
}
});
}

As JimL alluded to, I would give each element on your page a common class, give each element a unique data attribute like data-cid="1", iterate through each element grabbing the cids and calling the ajax function for each.
Id go a step further by using a promise to get all of the ajax responses then load all the data when the promise has been resolved (when all the ajax requests have been completed).
Here is a working example
The HTML:
<div id="loading_Paging"></div>
<div class="myElements" data-cid="1"></div>
<div class="myElements" data-cid="2" ></div>
<div class="myElements" data-cid="3" ></div>
<div class="myElements" data-cid="4" ></div>
<div class="myElements" data-cid="5" ></div>
<div class="myElements" data-cid="6" ></div>
<div class="myElements" data-cid="7"></div>
<div class="myElements" data-cid="8" ></div>
The jQuery:
$(function() {
var page = 'some string...'
loadData(page);
function loadData(){
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
// loop through each image element
// calling the ajax function for each and storing the reponses in a `promise`
var promises = $('.myElements').map(function(index, element) {
var cid = '&&cid=' + $(this).data('cid'); // get the cid attribute
return $.ajax({
type: "POST",
url: 'load.php',
data: "page=" + page +cid, //add the cid info to the post data
success: function(msg) {
}
});
});
// once all of the ajax calls have returned, te promise is resolved
// and the below function is called
$.when.apply($, promises).then(function() {
// arguments[0][0] is first result
// arguments[1][0] is second result and so on
for (var i = 0; i < arguments.length; i++) {
$('.myElements').eq(i).html( arguments[i][0] );
}
$('#loading_Paging').fadeOut('fast');
});
}
});
The PHP I used for my example:
<?php
if (isset($_POST['cid']) ){
// this is just a contrived example
// in your code youd use the cid to
// get whatever data you need for the current div
echo 'This is returned message '.$_POST['cid'];
}
?>

Related

Load more button not working and showing all the records on the page

I have a page and I am displaying the list(MAX 200 records) on my page using ajax.
I am using the below code to call the ajax and show the response on the page.
And the second script is for a button called "Load More". I have to show the 20 records on the page then the user clicks on load more than displays the next 20 records.
Now, My issue is, I am getting all the records and load more button
$(document).ready(function(){
$.ajax({
url: 'function21.php',
method:'post',
dataType: "json",
data:{action:"employeelist21"},
success: function(data){
$('#employeelist').append(data);
}
})
});
$(document).ready(function(){
var list = $("#employeelist21 li");
var numToShow = 20;
var button = $("#next");
var numInList = list.length;
//alert(numInList);
list.hide();
if (numInList > numToShow) {
button.show();
}
list.slice(0, numToShow).show();
button.click(function(){
var showing = list.filter(":visible").length;
list.slice(showing - 1, showing + numToShow).fadeIn();
var nowShowing = list.filter(":visible").length;
if (nowShowing >= numInList) {
button.hide();
}
});
});
PHP
function employeelist21($pdo)
{
$query=" sql query here";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
$data='';
$data='<ul><li>
<div class="box">
<div><span>Company</span></div>
<div><span>Industry</span></div>
<div><span>Name</span></div>
<div><span>Location</span></div>
</div>
</li>';
foreach($results as $key){
$data.='<li>
<div class="box">
<div><h4>'.$key['Industry'].'</h4></div>
<div><p>'.$key['industry_name'].'</p></div>
<div><p>'.$key['name'].'</p></div>
<div><p>'.$key['city'].'</p></div>
</div>
</li>';
}
$data.='</ul><div class="text-center">Load More</div>';
}
else{
$data.='No records available';
}
echo json_encode($data);
}
First, I would rather transfer back a list of data (not html) in json format and use that like an array, creating the HTML for it in javascript. BUT we don't always get what we want, so in this case I would assign an attribute to each set of 20 like this:
// at the top of your script (not in a function)
let perPage = 20, onGroup=0
// in your ajax function ...
success: function(data){
$('#employeelist').hide();
$('#employeelist').append(data);
$('#employeelist box').each( function(index) {
if (index===0) return; //header row
$(this).data('group',Math.floor(index-1/perPage))
});
$('#employeelist box').hide()
$('#employeelist box [data-group=0]').show()
$('#employeelist').show();
}
Then for the button, remove this from the PHP and make it an element under the results div
<div class="text-center">Load More</div>
Then in your script
$(document).ready(function() {
$("#next").click(function(){
$('#employeelist box [data-group='+onGroup+']').hide()
onGroup++;
$('#employeelist box [data-group='+onGroup+']').show()
if ($('#employeelist box [data-group='+(onGroup+1)+']').length ===0) {
$(this).hide();
}
});
});
Hard to test here, but let me know if it doesn't work

how to change the jquery code from onclick to show content always

I want to show a comments section always. Now a user has to click, to start the javascript code to display the content (onclick). a simple change to "onload" is not working. I tried it.
//Show reviews
function reviews_show(value) {
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value,
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
}
html code on .tpl page:
<li>Comments</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="comments_content"></div> </div>
If you mean with always -> on page load -> then this is the answer:
document.addEventListener("DOMContentLoaded", function(event) {
var value='{ID}'; // use value variable for your ID here
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value, // or replace to => data:'id={ID}',
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
});
Edit: Of course this was just an example how to make the browser to execute the jQuery.ajax on Page Loaded Completed. I edited the code and put the var value='{ID}' for your example. Make sure that there is your ID inserted (as it was inserted before in your onclick="reviews_show({ID});".

How can i pass a php variable to ajax

I have a auto load page and i need to be able to retrieve the data based on a variable as that variable must bring back a specific value. The code below is based on retrieving all the data.But i only need a select few which is based on the $list
Page.php
<?php
<div class="page-main ">
$query="SELECT * FROM page WHERE page_id='$list'";
$counting="SELECT * FROM page WHERE page_id='$list'";
$rows=mysqli_query($connection,$counting);
$rows_counts=mysqli_num_rows($rows);
$results=mysqli_query($connection,$query);
confirm_query($results);
?>
<div class="loader">
<img src="loader.gif" alt="loading gif"/>
</div>
</div> <!--close page main -->
here is the jquery passing to ajax (it is on same page)
$(document).ready(function(){
$('.loader').hide();
var load=0;
$.post("ajax.php",{load:load},function(data){ // somehow i need to pass $list to here
$('.page-main').append(data);
}); // close ajax
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$('.loader').show();
load++;
$.post("ajax.php",{load:load},function(data){
$('.page-main').append(data);
$('.loader').hide();
}); // close ajax
};
});// close window.scroll
});// close document.ready
this is ajax.php ( now here i am getting undefined variable $list, i need to pass $list i am not sure how to pass this $list from php to jquery to ajax.
$load=htmlentities(strip_tags($_POST["load"])) * 6;
$query="SELECT * FROM page WHERE page_id='$list' ORDER BY page_id DESC LIMIT ".$load.",6";
$result=mysqli_query($connection,$query);
confirm_query($result);
// after this while loop ect
try setting $list to a javascript variable. like:
var list=<?php echo $list?>;
then pass it the way you are passing var load.
A possible solution:
<script type="text/javascript">
var load=0;
$.ajax({
type: 'POST',
url: 'ajax.php',
data: ({load: load, list: <?php echo $list ?>}),
success: function(data) {
$('.page-main').append(data);
}
});
</script>

Loading query results into a Div

I have a div
<div id="loading"></div>
I then have some jQuery that loads in a page which is query heavy and therefore displays a spinner
<script>
$('#page1').click(function () {
// add loading image to div
$('#loading').html('<img src="loading.gif"> loading...');
// run ajax request
$.ajax({
type: "POST",
dataType: "html",
url: "client_reporting_01_data.php",
success: function (d) {
// replace div's content with returned data
$('#loading').html(d);
}
});
});
</script>
My trigger for this is a menu item:
<li id="page1" class = "<?php if($current_pgname == "client_reporting_01") echo 'active'; ?>">
C01: Summary Report
</li>
QUESTION:
I have multiple pages and multiple menu items
I'd like to be able to REuse the code I have here to pull the required pages back when the appropriate menu item is clicked.
So I would have another menu item
<li id="page2" class = "<?php if($current_pgname == "client_reporting_02") echo 'active'; ?>">
C02: Summary Report
</li>
and another page to call: client_reporting_02
I am just struggling with how to do the jquery to make this work
Somehow the jquery has to be able to read a page requested ie client_reporting_02_data.php
A further complication is how to actually move to that page and have it work. If say I am on pagexyz and i click the menu item for client_reporting_01 - it of course doesn not move there at present as a href="#"
One way to do it is bind to a class, rather than an id -
<script>
$('.reportLink').click(function () {
...
});
</script>
add the class, and a data attribute that holds the url (ie. data-url="client_reporting_01_data.php" and your li would now be
<li id="page1" class = "reportLink <?php if($current_pgname == "client_reporting_01") echo 'active'; ?>" data-url="client_reporting_01_data.php">
C01: Summary Report
</li>
now your script can be something like -
<script>
$('.reportLink').click(function () {
// add loading image to div
$('#loading').html('<img src="loading.gif"> loading...');
linkurl = $(this).data('url');//Probably want to sanitize and/or whitelist to prevent injection
// run ajax request
$.ajax({
type: "POST",
dataType: "html",
url: linkurl,
success: function (d) {
// replace div's content with returned data
$('#loading').html(d);
}
});
});
</script>
I am changing your already existing code slightly. If I understand what you want, the following will work. Instead of using the ID to call the function, add a generic class to all list items that are effected. I called it mypage here. Then there are a couple of ways to do it.
One way is: Instead of storing the url as is as a class, let the id tell you what url you are to look for. See the changes below for explanation:
// Generic class
$('.mypage').click(function () {
// add loading image to div
$('#loading').html('<img src="loading.gif"> loading...');
// if you need to include the 0 with child page numbers less than 10, you should change your ids accordingly.
var page=this.id.replace('page',''),
url= 'client_reporting_' + page + '_data.php';
// run ajax request
$.ajax({
type: "POST",
dataType: "html",
url: url,
success: function (d) {
// replace div's content with returned data
$('#loading').html(d);
}
});
});
Why not just delegate an event listener to the <ul> elements with an <a> anchor and put the url to load in the href? Like so;
HTML
<ul id="pages">
<li class = "reportLink <?php if($current_pgname == "client_reporting_01") echo 'active'; ?>">
C01: Summary Report
</li>
<li class = "reportLink <?php if($current_pgname == "client_reporting_02") echo 'active'; ?>">
Another Summary Report
</li>
</li>
Javascript
var $target = $('#loading');
$('#pages').on('click', 'a', function(event) {
event.preventDefault();
// add loading image to div
$target.html('<img src="loading.gif"> loading...');
$.ajax({
type: "POST",
dataType: "html",
url: this.href,
success: function (d) {
// replace div's content with returned data
$target.html(d);
}
});
});
You could even simplify your code by using .load like so:
Javascript - Simplifed version
var $target = $('#loading');
$('#pages').on('click', 'a', function(event) {
event.preventDefault();
$target
.html('<img src="loading.gif"> loading...')
.load(this.href);
});

Jquery, Call is only done one time successfully and after that it stays on the same result

I have a problem concerning my code which should change content in a div onclick "More News articles" as the change will happen only once. I see in Chrome Developer mode that it fires every click a request. What goes wrong?
Output.php
<?php
require_once('../pe13f/SSI.php');
require_once ('../PE13/smf_2_api.php');
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function MakeRequest(id)
{
$.ajax({
url : 'display.php',
data:{"id":id},
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
}
});
}
</script>
<div id="stream" class="bg4 roundedcrop shadow">
<div class="ph25 pv20">
<h1>News</h1>
<input id="streamcnt" name="streamcnt" type="hidden" value="" />
</div>
<div id="streamadd"></div>
<div id="streaminnern">
<?php
$num_recent = 5;
echo $num_recent;
?>
</div>
<div onclick="MakeRequest(<?php echo $num_recent; ?>);" id="streammore">More News articles</div>
</div>
backend php display.php
<?php
$num_recent = $_GET['id']+5;
echo $num_recent;
?>
Greetings Emil
Check the source that is produced by output.php. You'll find there onclick="MakeRequest(5);". Basically - on every click you call MakeRequest(5) which always fires call display.php?id=5 (you probably see that in your dev console).
Try something like this:
<script>
var lastId = 0; // var that stores last fetched ID
function MakeRequest(id)
{
if(!lastId) // if there is no last ID use the one from initial onclick
lastId = id;
$.ajax({
url : 'display.php',
data:{"id":lastId}, // note that we are using the lastId var
type: 'GET',
success: function(data){
$('#streaminnern').html(data);
lastId = data; // save fetched ID in our global var
}
});
}
</script>
The request is always the same. Suppose $num_recent is initially set to 5.
Then as per your code MakeRequest(5) will be executed. And your ajax call updates a div with class streaminnern. So the new id has no impact on the next ajax call. For the ajax request to be sent updated value you may set
$.ajax({
url : 'display.php',
data:{"id":$('#streaminnern').html()},
.................
});

Categories