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;
?>
Related
I'm thinking to do a image gallery dynamic and i'm looking for a solution simalar to facebook but using the url hash.
I would like receive dettails about this type of call ajax for get information dinamically without refresh the page, this is the right way for do what i'm looking for? There is some issue with the old browser?
<html>
<head>
//jquery.js
</head>
<body>
<!-- #nameimage is the name of the big image that will be loaded,
so this hash will be used for the call ajax. -->
<img src="url-thumb-image1">
<img src="url-thumb-image2">
<img src="url-thumb-image3">
<img src="url-thumb-image4">
<div class="image-big"></div>
</body>
</html>
Jquery
$(document).on('click','a', function(){
var hash = window.location.hash; // nameimage
// very simple ajax
BASE_URL = 'http://localhost/';
$.ajax({
type: "POST",
url: BASE_URL + 'get_image',
data: "name_image=" + hash,
success: function(result) {
// print result on div
$('.image-big').html(result);
},
error: function(){
alert('Error on ajax call');
}
});
});
PHP
<?php
$name_image = $_POST['name_image'];
$path = 'main_folder/image/';
echo '<img src="'.$path.$name_image.'.jpg">';
// and i can cache the results
?>
var hash = window.location.hash; // nameimage needs to instead look at the href of the anchor tag, the window location hash hasn't been updated yet at that point.
var hash = $(this).attr("href");
I think you need to remove the hash:
var hash = window.location.hash.substr(1);
But maybe the hash isn't defined yet at that moment. So it's better to use
$(document).on('click','a', function(e){
var hash = e.currentTarget.href.substr(1)
...
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.
I'm developing a PHP class for pagination using $_GET. It is standart, found from the web.
Here it works good :
page.php :
<form method ="GET">
<?php
$pages = new Pagination();
echo "<br/>";
?>
</form>
I want to use this page.php in index.php with ajax / jquery and staying in the index.php
<!DOCTYPE html>
<body>
<div id ="result"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.post('./page.php',
function (data) {
$('#result').html(data);
}
);
});
</script>
</body>
</html>
Is this possible way ?
Is it possible that instead of using jquery's $.post, that you can replace $.post with $.get?
So instead of $.post as you said its looking for $_GET['page']
So you could do something like this:
<script>
$(document).ready(function(e) {
var page_num = 1;
$('.nextpage').on('click',function(e){
e.preventDefault(); // stop the link from going anywhere
$.get('./page.php',
{
page: page_num // this is the same as $_GET['page']
},
function (data) {
$('#result').html(data);
page_num++;
}
);
});
$('.nextpage').click(); // emulate the click to get the first page
});
</script>
and in your body something like this:
Next page
It's worth noting that on your page.php you don't need to have that form as i cannot see it's going to be doing much
UPDATE
So to have the pagination manipulated on the index.php from page.php you could have page.php return a hidden div called .hidden_pagination along with its full content.
<script>
$(document).ready(function(e) {
$('.pagination').on('click','a',function(e){
e.preventDefault(); // stop the link from going anywhere
var next_page = $(this).attr('data-id'); // get the next page from the link data-id attribute
$.get('./page.php',
{
page: next_page // this is the same as $_GET['page']
},
function (data) {
$('#result').html(data);
$('.pagination').html($('#result').children('.hidden_pagination').html()); // add the new pagination to the current pagination
}
);
});
$('.nextpage').click(); // emulate the click to get the first page
});
</script>
<div class="pagination">
Next page
</div>
<div id="result">
this will be replaced with the ajax response
</div>
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?
I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>