load contents without reloading the page - php

I am using the following code, for loading contents without loading the page !
index.html
<html>
<head>
<script type="text/javascript">
// <![CDATA[
document.observe('dom:loaded', function () {
var newsCat = document.getElementsByClassName('newsCat');
for(var i = 0; i < newsCat.length; i++) {
$(newsCat[i].id).onclick = function () {
getCatPage(this.id);
}
}
});
function getCatPage(id) {
var url = 'load-content.php';
var rand = Math.random(9999);
var pars = 'id=' + id + '&rand=' + rand;
var myAjax = new Ajax.Request(url, {
method: 'get',
parameters: pars,
onLoading: showLoad,
onComplete: showResponse
});
}
function showLoad() {
$('newsContent').style.display = 'none';
$('newsLoading').style.display = 'block';
}
function showResponse(originalRequest) {
var newData = originalRequest.responseText;
$('newsLoading').style.display = 'none';
$('newsContent').style.display = 'block';
$('newsContent').innerHTML = newData;
}
// ]]>
</script>
</head>
<body>
<div class="newsCat" id="newsCat1">Politics</div>
<div class="newsCat" id="newsCat2">Sports</div>
<div class="newsCat" id="newsCat3">Lifestyle</div>
<div id="newsLoading">Loading
<img src="loading_indicator.gif" title="Loading..." alt="Loading..." border="0" />
</div>
<div id="newsContent"></div>
</div>
</body>
</html>
this page is for including the desired page in the index.php !
content-load.php
<?php
function stringForJavascript($in_string) {
$str = preg_replace("# [\r\n] #", " \\n\\\n", $in_string);
$str = preg_replace('#"#', '\\"', $str);
return $str;
$user = $_SESSION['userName'];
}
switch($_GET['id']) {
case 'newsCat1':
$content = include("politics.php");
break;
case 'newsCat2':
$content = include("sports.php");
break;
case 'newsCat3':
$content = include("lifestyle.php");
break;
default:
$content = 'There was an error.';
}
print stringForJavascript($content);
usleep(600000);
?>
PROBLEM FACING
it works fine, but when i am refreshing the page or submitting a form, the code refreshes, i mean the page which was include before refreshing, doesnot exists......
and i am really sorry about my ENGLISH, i know its horrible ! :)
pls help me php masters, i need ur help...

There are two ways to slove that problem.
You could do that on the client site with an hashtag what is curriently loaded and rebuild the page with that data or:
use the pushState API to manipulate the shown url in the address bar. Then you need to return the right data from the server after a reload.

This is behaviour by design. The Reload button will really reload the page - this includes resetting the page state.
In a freshly loaded page, you do not display a category - this is triggered only by user interaction after the page has finished loading.
A common workaraound is to store the chosen category in a cookie, auto-trigger the category load after the page has initialized.

Related

Infinite Scroll with history.pushState

I'm affronted to another jQuery problem. Well I'm beginning by my code to understand my issue here:
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
$(window).scroll(function(e){
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
$(window).scrollTop(60);
});
});
});
}
});
</script>
My problem is based on infinite scroll but instead of "append" I used html() function to replace content in a div called annonceis.
The idea is that when I'm scrolling to bottom of the page I get content of new page called index.php?page=1 2 3. And replace old content in de div annonceis with the new content that I get with jQuery, but when I scroll to the bottom I Get content of next next page ex when the current page is index.php?page=2 normally when I scroll to bottom I must get content of index.php?page=3 but here I get content of index.php?page=3 and instantly index.php?page=4 so the page display index.php?page=4.
The main idea is scrolling to bottom and get the content of the next page instead of pagination, but it must take care about history.pushState for SEO purpose and Google suggestions see http://scrollsample.appspot.com/items and that https://googlewebmastercentral.blogspot.com/2014/02/infinite-scroll-search-friendly.html.
Thank you very much in advance.
So, what you're after really is pagination combined with infinite scroll. What the provided example is doing is using .pushState() to track the users scroll using page Waypoints. Notice, once page X reaches the center point in the page, the .pushState() is triggered.
Secondly, if you look at the example's source code for any of the pages, you'll see it will only render the selected page, then using listeners on the .scroll it will append or prepend content as needed.
So, at it's core, this is really just simple pagination. The infinite scroll feel is simply added on top for user experience. Basic overview to do this would look something like this:
Model or Controller
Your PHP file or whatnot, that runs the actual queries - class based for ease of use. The class will contain one function to grab a set of posts based on a request page. JavaScript will handle everything else.
<?php
Class InfiniteScroller {
// Set some Public Vars
public $posts_per_page = 5;
public $page;
/**
* __construct function to grap our AJAX _POST data
*/
public function __construct() {
$this->page = ( isset($_POST['page']) ? $_POST['page'] : 1 );
}
/**
* Call this function with your AJAX, providing what page you want
*/
public function getPosts() {
// Calculate our offset
$offset = ($this->posts_per_page * $this->page) - $this->posts_per_page;
// Set up our Database call
$SQL = "SELECT * FROM my_post_table ORDER BY post_date ASC LIMIT " . $offset . ", " . $this->posts_per_page;
// Run Your query, format and return data
// echo $my_formatted_query_return;
}
}
?>
AJAX Call
The next thing you'll want to take care of is your frontend and JavaScript, so your AJAX call can sit in a function that simply calls the above method and takes a page parameter.
<script type="text/javascript">
function getPageResults( page = 1, arrange = 'next' ) {
$.ajax({
url: url;
type: "POST",
data: "?page=" + page,
success: function(html) {
/* print your info */
if( arrange == 'prev' ) {
$( '#myResults' ).prepend(html);
else if( arrange == 'next' ) {
$( '#myResults' ).append(html);
}
},
error: function(e) {
/* handle your error */
}
});
}
</script>
The HTML View
Your HTML would be fairly basic, just a place to hold your displayed results and some creative triggers.
<html>
<head>
</head>
<body>
<div class="loadPrev"></div>
<div id="myResults">
<!-- Your Results will show up here -->
</div>
<div class="loadNext"></div>
</body>
</html>
Loading the Page You Want
In basic summation, the last piece of your puzzle is loading the page requested based on the querystring in the URL. If no querystring is present, you want page 1. Otherwise, load the requested page.
<script type="text/javascript">
$( document ).ready(function() {
var page = <?php echo ( isset($_GET['page'] ? $_GET['page'] : 1) ?>;
getPageResults( page, 'next' );
});
</script>
After that you can set up some creative listeners for your previous and next triggers and call the getPageResults() with the needed page, and the next or prev attribute as needed.
This can really be done in a much more elegant sense - look at the JS from the example you provided: http://scrollsample.appspot.com/static/main.js
Cleaning it up
Once you have the basic architecture in place, then you can start altering the .pushState() as well as changing out the canonical, next, and prev <link rel> header items. Additionally at this point you can start to generate the next / prev links you need, etc. It should all fall into place once you have that basic foundation laid.
Hey Bro #LionelRitchietheManatee Finnaly I have resolved the problem this is the code that I used.
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
var loaded = true;
$(window).scroll(function(e){
if(($(window).scrollTop() + $(window).height() == $(document).height())&&(loaded)) {
loaded = !loaded;
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
loaded = !loaded;
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
loaded = !loaded;
$(window).scrollTop(60);
});
});
});
}
});
</script>
I had added a new var called "loaded" with initial value as TRUE, and it will be updated to FALSE state when content is loaded, and to the TRUE state when we begin scrolling.
I'ts very primitive as solution not very clean work as you did but it solved my problem.
Thank you anyway for your help, you are the BOSS.

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

Retrieving page with anchor AJAX not working in IE

We released a site a couple of weeks ago and we are now getting complains that the website doesn't work in Internet Explorer 6-10.
Im using jQuery version: 1.11.0
We are running AJAX to load each page with an anchor. For example. www.site.com/#page2
Im trying to debug the code and see where it fails but I have no idea what is wrong.
The problem people are having is simple, the page doesn't load. All other code except the page call is working. So basically the page is empty.
This is a simplified version of the code:
function retrieve_page(link, lang){
event.preventDefault();
var id = link;
if(id){
document.location = "#"+id;
} else {
document.location = "#hem";
}
if(window.location.hash.substring(1) != "undefined") {
var page = window.location.hash.substring(1);
} else {
var page = "hem";
}
var content;
var request = $.ajax({
type: "GET",
url: "ajax/retriever.php",
data: { page:page },
success: function(data) {
content = data;
}
});
request.done( function () {
$('#page').html(content);
});
}
and this is the ajax/retriever.php file
<?php
$page = $_GET["page"];
$path = "../pages/".$page.".php";
$config = "../core/config.php";
if(!file_exists($path)){
require_once $config;
echo "<div id='no_page'><h1 style='display: block'>".$lang["ERROR"]."</h1><a href='index.php'><h2>".$lang["ERROR_RETURN"]."</h2></a></div>";
exit;
} else {
require_once $config;
require_once $path;
exit;
}
?>
The AJAX function call is example:
<a onclick="retrieve_page('page1', 'sv')">Page1</a>
Thanks in advance!
Can't see how i missed it. Well i solved the issue with simply removing event.preventDefault();

HTML Get URL parameter

I want to change url without reload the page because Im using AJAX function to reload a div.
The problem is that when the AJAX load the div, it doesn't read the url parameter.
My code (I've already load the jquery.js etc.) :
index.php
<a href="#page=1" onClick='refresh()'> Link </a>
<a href="#page=2" onClick='refresh()'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh() {
$("#test").load("mypage.php"); //Refresh
}
</script>
<div id="test">
</div>
mypage.php
<?php
if (isset($_GET['page'])){
$page = $_GET['page'];
}
echo $page;
?>
PHP can't read the fragment without reloading the page. This can be done using JS.
Below the script I use to read the parameter values without reloading the page. I don't think it's the best method there is, as there are plugins you could use to do the same (and much more), but it works. I found it online some time ago, but unfortunately I don't remember where :(
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.hash.slice(1);
urlParams = {};
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
})();
You would then get the parameter value with:
urlParams['page']
If you will work a lot with hash urls, you should check out this plugin: http://benalman.com/projects/jquery-bbq-plugin/
Getting after # hash tag:
With PHP (Required page load)
parse_url() fragment index thats you need
$url = parse_url($_SERVER['REQUEST_URI']);
$url["fragment"]; //This variable contains the fragment
With jQuery: (Not required page load)
var hash = $(this).attr('href').split('#')[1];
var hash = $(this).attr('href').match(/#(.*$)/)[1];
Demo (Used without hash tag)
index.php
Link | Link2
<script type="text/javascript">
$(".myLink").click(function(e) { // when click myLink class
e.preventDefault(); // Do nothing
var pageId = $(this).attr('data-id'); // get page id from setted data-id tag
$.ajax({
type:'POST',
url:'mypage.php', // post to file
data: { id: pageId}, // post data id
success:function(response){
$("#test").html(response); // write into div on success function
}
});
});
</script>
<div id="test"></div>
mypage.php
<?php
// get with $_POST['id']
echo "Loaded Page ID: ".($_POST['id'] ? $_POST['id'] : "FAILED");
?>
You need to pass a page parameter to the URL you're requesting.
Try this:
<a href="#page=1" onClick='refresh(1)'> Link </a>
<a href="#page=2" onClick='refresh(2)'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh(pageNumber) {
$("#test").load("mypage.php?page="+pageNumber); //Refresh
}
</script>
It is possible for you to pass parameters through the load() function in jQuery.
There are 2 common ways of doing so:
Using get:
JS:
$('#test').load('mypage.php?page=mypage');
PHP:
<?php
if (isset($_GET['page']))
{
$page = $_GET['page'];
}
echo $page;
?>
Or using data as a post:
JS:
$('#test').load('mypage.php', { page: mypage });
PHP:
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
echo $page;
?>

How to append additional data in a specified div using php / ajax

I want to know if there is a way to display an external php file after clicking on a link, and then display another external file right below(not INSTEAD of) it after a different link was clicked. Here is my code.
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery- 1.2.6.pack.js"></script>
<script type="text/javascript" src="core.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li id="home">DOWNLOADS</li>
<li id="tutorials">ERRORS</li>
</ul>
</div>
<div id="content">
</div>
</body>
</html>
core.js
//On load page, init the timer which check if the there are anchor changes each 300 ms
$().ready(function(){
setInterval("checkAnchor()", 100);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor)
query = "page=1";
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
}
}
downloads.php
<b>DOWNLOADS</b>
errors.php
<b>ERRORS</b>
callbacks.php
<?php
//used to simulate more waiting for load the content, remove on yor projects!
sleep(1);
//Captures the petition and load the suitable section
switch($_GET['page']){
case "errors": include 'errors.php'; break;
case "downloads": include 'downloads.php'; break;
default: include 'downloads.php'; break;
}
?>
This works perfectly except it uses a switch and I want to be able to see both errors.php and downloads.php at the same time, not only one or the other.
EDIT
Pseudo code to make it clearer:
If download is clicked show download.php only. If error is clicked show error.php only(right after downloads.php) and don't remove downloads.php or any other external file that may or may not be included on the main page already.
Any suggestions?
p.s. I've looked through many, many threads about this and that's why I can't post all the code I've tried (sorry I can't include links either, last time my question was downvoted for doing that...>:/) so I can promise I've done my homework.
p.s.s. If you think this deserves a down vote please be kind enough to explain why. I'm open to criticism but just thumbs down is not helpful at all.
EDIT:
Updated core.js to
$(document).ready(function(){
$('#menu li a').click(function() {
var currentAnchor = $(this).attr('href');
if(!currentAnchor)
var query = "page=1";
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
return false;
});
});
EDIT:
[The confusing parts removed here]
--
EDIT:
core.js (revised)
//On load page, init the timer which check if the there are anchor changes each 300 ms
$(document).ready(function(){
$('#menu li a').click(function() {
var currentAnchor = $(this).attr('href');
if(!currentAnchor)
var query = "page=1";
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
return false;
});
}​​​);​​​
--
EDIT:
This one will "append" data [coming from either downloads or errors] to the existing content.
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
Hope this helps.
If you want to show both pages at once, in your callbacks.php page you should be able to do something like this (all I did was remove the switch statement):
include 'errors.php';
include 'downloads.php';
Any reason why you can't do this?

Categories