I have some code that iterates through some database results and displays them, as such...
Note: article item.php just echoes the results with some formatting.
<ul class="post-column">
<?php
foreach ($data as $lineitem):
$type = $lineitem['type'];
if($type == "article"){
require('php/articleitem.php');
}
endforeach;
?>
</ul>
When I get to the bottom of the page, I want to do an AJAX DB call to get further results...
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 700) {
startpoint = startpoint + 10;
processing = true;
$.ajax({
url: "AJAX/moritems.php",
type: "post",
async: false,
//this is where we define the data that we will send
data: {
startpoint: startpoint,
},
success: function (data) {
},
});
processing = false;
}
I want to then use the DB results to display more data below the data I've already displayed on the screen, but because I've displayed the result thus far in PHP, how would I do that? Would I have to use AJAX to load a new php page with results, then use javascript to add it to the existing page at the bottom of the results?
The answer is yes. Example:
function load() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML += xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", yoururl, true);
xmlhttp.send();
}
You need to define yoururl and link the function to the click event of your paging button or run it when you scroll.
Related
I'm using scrolling instead of pagination but my problem is that it still loading even the data already there and no more data found, so the scrolling down will never stop, and I think because I can't set the condition that if reached to the last page then stop loading
to check if the json html is empty is difficult because it contains html divs
I hope you can help me to reach to the end of content then stop scrolling
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page) {
$.ajax({
url: '?page=' + page,
type: "get",
beforeSend: function() {
$('.ajax-load').show();
}
}).done(function(data) {
if(page == " ") {
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$("#load_data").append(data.html);
}).fail(function(jqXHR, ajaxOptions, thrownError) {
alert('server not responding...');
});
}
/*Show Hide Cousines*/
$('#showcuisine').on('click', function (event) {
event.preventDefault();
$(".cuisines").show();
$("#showcuisine").hide();
$("#hidecuisine").show();
});
$('#hidecuisine').on('click', function (event) {
event.preventDefault();
var allcuisines = jQuery('.cuisines');
for (var i = 5; i < allcuisines.length; i++) {
$('#cuisine' + i).hide();
}
$("#showcuisine").show();
$("#hidecuisine").hide();
});
Controller
if ($request->ajax()) {
$view = view('store-search.listing', compact(
'stores','storedays','cuisines'
))->render();
return response()->json(['html'=>$view]);
}
When there is no more data to receive you can return null or false instead of view.
Then replace
if(page == " ") {
$('.ajax-load').html("No more records found");
return;
}
with:
if(!data) {
$('.ajax-load').html("No more records found");
return;
}
You should also include a variable isLastPageLoaded = false and set it to true wen last page is reached. Before making new AJAX request you should check if this is still false. If it's true then you don't need to load new records.
Do I understand correctly that already existing records get duplicated?
check with if condition on api side if zero record fetching then return null.
and then put this on your ajax done function
if(data == null) {
$('.ajax-load').html("No more records found");
return;
}
Solved,
I have to put the foreach in a div with no other html up to the foreach
Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...
Currently I got this code:
function post_positive(id) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("post"+id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","post_review.php?id="+id+"&type=positive",true);
xmlhttp.send();
return false;
}
For my ajax call I just the function post_positive(). Sometimes it shows the result, sometimes with page refresh, sometimes nothing.
You use jQuery ajax() method for ajax it is easy to understand and working properly
function post_positive(id){
$.ajax({
type:'get',
url:'post_review.php',
data:{ 'id':id,'type':'positive' },
success:function(result){
$("#post"+id).text(result);
}
});
}
I have a comments board on my page, to which I load different topics according to the page the user is on with XMLHttpRequest in a changeTopic() function. I originally had this at the end of my submit form php:
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_POST['page']);
The problem is that I don't want to refresh the whole page, only the DIV that contains the messages. I tried running the changeTopic() function by inserting it inside script tags with echo. For one, I couldn't get .$_GET['topic']. working inside echo even if I made a variable of it first, but also I tried running the function by hard inserting one of the possible values with the following results:
1) While the messages section refreshed right, I lost the form as it's contained in the index.html while I only load the messages from an external gettopic.php with query string.
2) I got a weird result where I lost an external file that was loaded into a completely different div altogether. This file changes the hash of the main page, which is checked with every refresh and the right file is loaded according the hash, so using the whole page refresh never resulted in this.
// EDIT
function changeTopic(topic) {
if (topic=="") {
document.getElementById("messagelist").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("messagelist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", "gettopic.php?t="+topic,true);
xmlhttp.send();
}
The main application on my page is a SVG map which I've done with RaphaelJS. The user can load information pages into another div 'info' from this SVG map. The pages are loaded with a similar function which in addition changes the #hash and runs the changeTopic() as well to change the message board so people can have a conversation about each topic.
The PHP form takes the normal filled info as well as the hidden 'pageid' which is set by the current page the user is browsing, and sends it to the database. The different messages are sorted by this pageid so the changeTopic() function only brings the right messages: gettopic.php?t=topic ('pageid').
After submitting the form I'd like only the messagespart to refresh and the form to clear. At the moment it's either a whole page refresh (user looses their position on the SVG map) or partial refresh where I lose the form (get a blank spot instead) and that weird information-page missing.
you can do something like this:
var ajaxfoo = function(obj) {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e) {
xmlHttp = null;
}
}
}if (xmlHttp) {
obj.method = obj.method.toUpperCase();
xmlHttp.open(obj.method, obj.url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if(obj.method == 'POST') {
if(typeof(obj.params) != 'undefined') {
xmlHttp.setRequestHeader("Content-length", obj.params.length);
}
}
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
var json = eval(xmlHttp.responseText);
if(json.success) {
if(typeof(obj.success) == 'function'){obj.success(xmlHttp.responseText);}
}
else {
if(typeof(obj.failure) == 'function') {obj.failure(xmlHttp.responseText);}
}
}
};
if(obj.method == 'POST' && typeof(obj.params) != 'undefined') {
xmlHttp.send(obj.params);
}
else {
xmlHttp.send(null);
}
}
};
function callfoo(topicname) {
ajaxfoo({
method: 'GET',
url: 'gettopic.php?t='+topicname,
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
failure: function(response) {
var json = eval(response);
alert('failure callback function! '+json.data);
}
});
}
and in
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
you can add your innerHTML stuff :)
the gettopic.php
should then echo something like:
{success: true, data: [{id: 1, "title": "test title", "description": "moo"},{id: 2, "title": "test title", "description": "moo"},{id: 3, "title": "test title", "description": "moo"}]}
And the you can access this by calling
json.data[0].title
json.data[1].title
json.data[2].title
json.data[0].description
...
so you can simply build your innerHTML stuff by doing something like
doc....innerHTML = '<h2>'+json.data[0].title+'</h2>';
Use jQuery - great tool. It could look like
$(function(){
//when you want to reload your div, just put this line
$("#div_element").load('your_new_page.php');
});
and that's it !
I'm quite confused about what you are doing, but XMLHttpRequest should be the one running changeTopic() in the readystatechange handler.