I have gotta website powered by a set of jQueries; Dynamically loading the contents with a set of menu buttons.
Now, all I want to know is this:
Have you seen in blogger? The url is like
blogger.com/blogger.g?blogID=abcd#id
For the #id, if you put #overview it shows the stats. If you put #allposts it shows all the posts and similarly the content varies depending only on the #id in the url. I've seen many websites use this method to provide PermaLinks too.
How can I do it? for each menu button I provided an #id, which if passed in the url I need to switch to that particular menu.
Note : I use PHP, js, jQuery and HTML5 +/- Ajax
PS: Please, do not say you can use this and that! I'm a kinda middle of a knowledge i.e I'm not a pro. So please provide me with some algorithms or code.
Thanks in advance :)
window.location.hash will contain the hash value in the URL (#id, #overview, etc...). You can then use javascript that runs when your page loads to check the value of window.location.hash and based on what it contains, you can modify your page, using ajax calls if retrieving data from the server is necessary.
The hash value is not sent to the server so it must be client-side code that processes it.
As for specific code, you would use something like this;
$(document).ready(function() {
switch(window.location.hash) {
case "#id":
// code here
break;
case "#overview":
// code here
break;
default:
// code here
break;
}
});
What specific code goes in there obviously depends upon what you're trying to do. If you need to get data from your server, then you would issue ajax calls to retrieve that data.
This are called hash values which are not sent by the browser to the server, they can only be accessed by javascript.
They can be retrieved by
var hash_val = window.location.hash;
Javascript also provide event for hash change
window.onhashchange = function(){
}
And if you want it to modify content then
window.onload=function()
{
var hash_val = window.location.hash;
//do more ajax stuff here
}
Related
I am using Ajax and hash for navigation.
Is there a way to check if the window.location.hash changed like this?
http://example.com/blah#123 to http://example.com/blah#456
It works if I check it when the document loads.
But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).
It shows inside the address box, but I can't catch it with JavaScript.
The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.
Update to keep this answer fresh:
If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.
$(window).on('hashchange', function() {
//.. work ..
});
The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.
With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).
In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.
This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.
HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:
Internet Explorer 8
Firefox 3.6
Chrome 5
Safari 5
Opera 10.6
Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
EDIT -
Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/
There are a lot of tricks to deal with History and window.location.hash in IE browsers:
As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.
Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.
However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.
If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)
I know this isn't a real response, but maybe IE-History notes are useful to somebody.
Firefox has had an onhashchange event since 3.6. See window.onhashchange.
I was using this in a react application to make the URL display different parameters depending what view the user was on.
I watched the hash parameter using
window.addEventListener('hashchange', doSomethingWithChangeFunction);
Then
function doSomethingWithChangeFunction () {
let urlParam = window.location.hash; // Get new hash value
// ... Do something with new hash value
};
Worked a treat, works with forward and back browser buttons and also in browser history.
You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.
Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.
The code will look like this:
window.location.watch(
'hash',
function(id,oldVal,newVal){
console.log("the window's hash value has changed from "+oldval+" to "+newVal);
}
);
Then you can test it:
var myHashLink = "home";
window.location = window.location + "#" + myHashLink;
And of course that will trigger your observer function.
Another great implementation is jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.
Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!
var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123
function TrackHash() {
if (document.location != page_url + current_url_w_hash) {
window.location = document.location;
}
return false;
}
var RunTabs = setInterval(TrackHash, 200);
That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.
I've been using path.js for my client side routing. I've found it to be quite succinct and lightweight (it's also been published to NPM too), and makes use of hash based navigation.
path.js NPM
path.js GitHub
SHORT and SIMPLE example
Click on buttons to change hash
window.onhashchange = () => console.log(`Hash changed -> ${window.location.hash}`)
<button onclick="window.location.hash=Math.random()">hash to Math.Random</button>
<button onclick="window.location.hash='ABC'">Hash to ABC</button>
<button onclick="window.location.hash='XYZ'">Hash to XYZ</button>
I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?
I need to redirect users to a unique url when they visit a specific link which corresponds to a certain/row/column in the mysql database.
Here is what I mean:
The mysql database has a table table123 with a row id 123 and inside a column name "column123".
This row and column correspond to the webpage1.html
Normal javascript redirection is like this:
<script>location.replace('http://website.com/webpage2.html');</script>
What I need to do is extract the value from column123 of the webpage1.html and add it to the redirection url, so it would redirect specifically with that value.
For example:
<script>location.replace('http://website.com/webpage2.html/go/dbtable123row123column123value');</script>
This redirection script will be placed on top of the php page that will call the other php pages, so it has to be dynamic every time, thus the redirection script has to use dynamic placeholder, not static value, except the domain name.
Thanks
If the table really is mysql table and the javascript has no way to access that information, follow other suggestions and deal with it on the server-side. If somehow, the table data are printed on the html document where you want the redirect to take place then you can consider the following. (Though, it would really make more sense to manage this server-side).
Assuming you have given unique id to your column and assuming that the table is on the web page that you have your location.replace call on.
location.replace("http://website.com/webpage2.html/go/" + $('#column123').text())
Without jQuery, you could use
document.getElementById('#column123').innerHTML (or text?)
If it is not practical to assign an id to the column, you can possibly use some jQuery selector magic with :eq
location.replace("http://website.com/webpage2.html/go/" + $('#dbtable123 > tr:eq(1) > td:eq(3)').text())
(none tested)
Assuming you can't redirect in PHP for whatever reason, here's what I'd do. Grab the proper web page from your database using AJAX. I'd suggest using a library such as jQuery to help you do that. If you use jQuery it'll look something like this:
$(function() {
$.get(
'/script/that/queries/db.php',
'your=query_string&goes=here',
function(data) {
if(data.url.length > 0) {
location.href = data.url;
}
},
'json'
);
});
You didn't specify when you want this redirect to fire, so I just put it in the standard body onload. Anyway, after you write that $.get() function call, then in your /script/that/queries/db.php, you'll want to perform your database query based on the get variable(s), and print a JSON encoded array with the valid page you want to redirect to:
$json = array('url' => '/webpage2.html');
print json_encode($json);
Of course I've just written some pseudo code, but hopefully it'll help get the idea across. You'll want to make sure you validate/sanitize all info being querying the database, etc.
Do it simply.Make dynamic url with php script.
header('Location: http://website.com/'.$table123row123column123);
I'm trying to do something that goes far over my current skills yet I believe I can do it, I would be imensely thankfull if you point me to an already developed script for this matter.
My question comes from what runs first? Javascript or php? because I need to asynchronosly include a php file into the page.
My idea is this, if user has a screen width wider then 1024, draw an extra fixed position div, if not, don't draw it. That div is supposed to take in a flash object with a clickable link.
My idea would be to:
Get resolution with javascript.
Use jQuery to send ajax json var into .php file that stores res vars into a session cookie.
Read the cookie with php, decide to include the extra .php file or not. That file should then eco the extra div with flash object.
Is this possible? Is there an easier way? Since this is to include in a Zencart personal store of mine, does it conflicts with the zencart cookie session or can a user have more then 1 type of session cookie per website? it can right?
Best Regards, any help appreciated,
Joricam
Yes, it's possible - but now in the way you're describing. PHP runs server side and Javascript runs client side, i.e. PHP is executed before any Javascripts. However, nothing says you cannot do this only with Javascript - and it would actually be trivial to solve with jQuery (as you tagged the question with it). Just let your Ajax called PHP-page return the inline HTML, and print it with jQuery instead. No need for cookies, either.
PHP runs first because the page hasn't loaded yet and javascript is run user-side, but once the page is loaded, ajax allows you to make calls to a php script and recieve a result that you can then add to the page via javascript.... so yes it's doable:)
Sessions can contain as many keys as you need them to, just name them something specific
<script language="javascript">
if (window.location.search == "") {
window.location.href = window.location + "?width=" + screen.width + "&height=" + screen.height;
}
</script>
This will redirect the page you try to access to the same page but sending parameters to the page.
Then you would be able to:
<?php
$width = $_get['width'];
$height = $_get['height'];
?>
Ok, I'm not sure how this is normally done. But I've got a script that basically empties a div of content and then loads content from a div from a separate webpage, without reloading the current page. This works great.
It's taken from this example actually, from net tuts (great site btw)
http://nettuts.s3.amazonaws.com/011_jQuerySite/sample/index.html
And the guy who wrote this even though about handling the url's since the url don't change when using his method. So he wrote a javascript snippet that looks up the url and loads the content accoringly. Which is not working btw.
But I was thinking about people who don't have javascript enabled, or iPhone and iPad users ;)
Copying URLs and sending to a friend won't work at all.
So how is this typically done? And can it be done without javascript? Possibly by php?
I'm using this code basically:
$(document).ready(function() {
// Check for hash value in URL
var hash = window.location.hash;
if(hash==href.substr(0,href.length)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
$('.dynload').live('click', function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').fadeOut('fast',loadContent);
$('#ajaxloader').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').fadeIn('fast',hideLoader());
}
function hideLoader() {
$('#ajaxloader').fadeOut('normal');
}
return false;
});
See Tabtastic
In a nutshell, link to the id of the element you want to go to, and don't hide the content if JS isn't available.
You can't access the hash-part of the URL through PHP. You can only access that from the browser.
However, you could just change the code to using a normal GET query string instead. So put whatever you put behind the # symbol, behind ?hash= in the URL instead and work with it that way.