i look this tutorial
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
but i don't understand how to make this work with php file with sql, echo ""; etc
If someone can explain, i try everything and nothing appears
Thanks :)
var default_content = "";
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pagesContent').html();
setInterval("checkURL()", 250);
});
var lasturl = "";
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if (hash == "")
$('#pagesContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
url = url.replace('#page', '');
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page=' + url,
dataType: "html",
success: function (data) {
if (parseInt(data) != 0) {
$('#pagesContent').html(data);
$('#loading').css('visibility', 'hidden');
}
}
});
}
load_page.php
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');
else echo 'There is no such page!';
?>
demo.html
< a href="#page1">Page1< /a>
< a href="#page2">Page2< /a>
< a href="#page3">Page3< /a>
< a href="#page4">Page4< /a>
<div id="pageContent">
//loaded ajax page
</div>
in this scenario , link > index.html#page1 will load file 'pages/page_1.php'
but in main index.html just can load html code , not php syntax .
Can I use php command in this case ?
So it looks like the problem here is that in the tutorials example, they simply use an HTML file. For this, file_get_contents() will work fine. However if you want your server to parse PHP code before serving it to the user, you should use the include() function.
From the documentation :
The include statement includes and evaluates the specified file.
The file_get_contents() function behaves silghtly differently :
file_get_contents — Reads entire file into a string
It simply reads the contents of the file, the PHP code is not evaluated/executed/interpreted...
Related
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();
I'm working with AJAX on a website and I'm currently making some pages to load on a certain div: "pageContent". Now I have another content I want to be opened on another div: "reproductor". I want to open 'page' in 'pageContent' div and 'play' in 'reproductor' div. I don't know how to modify my script.js and load_page.php files in order to make it work. Here's what I got:
HTML:
<script type="text/javascript" src="js/script.js"></script>
PAGE
PLAY
<div id ="pageContent"></div>
<div id="reproductor"></div>
script.js:
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
load_page.php:
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else
echo 'There is no such page!';
?>
I forgot to mention: I have my 'pages' content in a folder named 'pages' and my 'play' content in another named 'plays'.
Thanks for your help!
The easiest way to load content from a resource that serves HTML into an element is to use load:
$('#reproductor').load('public_html/plays/play_1.html', function(){
//stuff to do after load goes here
});
You could also apply this technique to the other div you are trying to load content into.
If I understand, your have two groups of links (for pages and a play list) each one to be loaded in a different container. Here is something you can try: mainly I eliminated the global variables and put the current hash inside each containter's data, and separated the management of the two groups of links.
In this code I supposed you have a separate load_play.php file. If not, then you can use the same page for both kind of links, but you'll have to merge loadPlay with loadPage, change loadPage(newHash) to loadPage(newHash, linkType) and change the ajax parameter from 'page='+newHash to 'number='+newHash+'&type='+linkType, and do the corresponding changes server side in your PHP page. I would recommend you to create two separate PHP files in order to manage the two types of content.
I remember you where doing something with the hash of the current page's url, you can still set it in the ajax's success, inside the loadPage function.
Here is a working sfiddle example with some console calls (open browser's console) but without the ajax call.
UPDATE:
I updated the code, so your can manage the dynamically added links (new content loaded via AJAX) and fixed the management of urls with hashes, which was broken because of the new code.
<div id="#page">
PAGE 1
PAGE 2
PLAY 1
PLAY 2
PLAY 3
<div id ="pageContent"></div>
<div id="reproductor"></div>
</div>
And this is the javascript:
$(document).ready(function(){
$('#pageContent').data('currentPage', '');
$('#reproductor').data('currentPlay', '');
//This will allow it to work even on dynamically created links
$('#page').on('click', '.pageLink', function (e){
loadPage(this.hash);
});
$('#page').on('click', '.playLink', function (e){
loadPlay(this.hash);
});
//And this is for managing the urls with hashes (for markers)
var urlLocation = location.hash;
if(urlLocation.indexOf("#page") > -1){
$('.pageLink[href='+ urlLocation +']').trigger('click')
}
});
function loadPage(newHash)
{
//This is the current Page
var curHash = $('#pageContent').data('currentPage');
//and this is the new one
newHash = newHash.replace('#page', '');
if(curHash===newHash){
//If already loaded: do nothing
return
}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg).data('currentPage',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
function loadPlay(newHash)
{//Similar to loadPage...
var curHash = $('#reproductor').data('currentPlay');
newHash = newHash.replace('#play', '');
if(curHash===newHash){return}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_play.php",
data: 'play='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#reproductor').html(msg).data('currentPlay',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
Check this and comment if this is what you need, or I got something wrong :)
There are a number of reasons why the following is not an ideal solution. The most glaring would be security - by modifying the href attribute of the link before clicking it, the user can certainly get your server to serve up any html on your server.
EDIT I've removed my original answer, because I can't recommend it's usage.
As Asad suggested, you can also use jQuery load and pass it the relevant url using some of the code above
function loadPage(url)
{
// remove the hash in url
url=url.replace('#','');
// extract page or play - only works for four letter words
var contentType=url.substr(0,4);
// extract the number
var contentId=url.substr(4);
if ( $contentType == "page") {
$("#pageContent #loading").css('visibility','visible');
$("#pageContent").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#pageContent #loading").css('visibility','hidden');
} else if ( $contentType == "play") {
$("#reporductor #loading").css('visibility','visible');
$("#reproductor").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#reporductor #loading").css('visibility','hidden');
}
}
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 ...
I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});
I have two issues I'm trying to work though.
The first is I'm trying to set the URL to follow the AJAX crawling scheme as described by google: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=174993
when I load my two PHP pages for searching I currently just call:
mysite/search_advanced.php
mysite/mysite/search_basic.php
I'm trying to turn these URL into:
mysite/#!/search=advanced
mysite/#!/search=basic
I need the ability to call these URLs directly and have them generate the correct page.
My second issue is I'm unable to load my pages into a div tag because each search page has it's own set of jquery functions for onclick events.
Here is how I would like to load my search_advanced page into a div tag with an id of main:
$('#search_advanced').click(function(e) {
$('#main').load("search_advanced.php");
return false;
});
The header portion of my search_advanced.php page contains this:
<?php session_start();
include_once('functions/dbconn.php');
include_once('functions/functions.php');
include_once('check.php');
check_login('3');
$profile = getProfile($_SESSION['uid']);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$params = $_POST;
if(isset($_POST['pg'])) {
switch($_POST['pg']){
case '10':
$pg=10;
break;
case '25':
$pg=25;
break;
case '50':
$pg=50;
break;
default:
$pg=10;
}
}
}
function getPagination($start, $pg, $count) {
$pager = "";
$pages=(int)ceil($count/$pg);
$current_page = (int)ceil(($start+1)/$pg);
if($current_page > 1) {
$prev_page= ($current_page-2)*$pg;
$pager .= "<span class=\"prev\">Prev</span> ";
}
for ($i=1; $i<=$pages; $i++) {
if($current_page == $i) {
$pager .= '<strong>'.$i.'</strong> ';
}
else {
$page_start = ($i-1)*$pg;
$pager .= "<span class=\"page_no\">".$i.'</span> ';
}
}
if ($current_page < $pages) {
$next_page = ($current_page)*$pg;
$pager .= "<span class=\"next\">Next</span> ";
}
return $pager;
}
$title="Advanced Search";
$ready_script = <<<READY_SCRIPT
$(".country").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "GET",
url: "ajax_region.php",
data: dataString,
cache: false,
success: function(html){
$("#state_id").html('<option value="-1">Any</option>'+html);
}
});
});
$(".pager").click(function(){
// my code here
});
$('#advanced_search').click(function(){
// my code here
});
READY_SCRIPT;
Currently my $ready_script variable gets passed to my header.php page that gets executed from this:
$(document).ready(function() {
<?php if (isset($ready_script)) {echo($ready_script);} ?>
}
I only want to call my header.php once now and load all my pages into my main div tag so I'm not continually hitting the server with uneeded calls everytime. After my onclick menu event is there a better way to initialize my jquery functions for the specific page I'm loading?
Any thoughts would be greatly appreciated.
Thanks,
-Paul
Separate your javascript from your content by putting the scripts into .js files. After you load your content, load your scripts:
$('#main').load("search_advanced.php", function () {
$.ajax({ url: "search_advanced.js", dataType: "jsonp" });
});
If you load the js at the same time as the content, your scripts could run prematurely.