Bookmarkable Ajax - html

I'm paginating a list of items, and currently the page listed on page load is set by a GET variable (e.g. www.example.com/page.html?page=2). I want to switch it to ajax, but I'm worried users won't be able to bookmark the page they want to view.
Is there a way I can update the URL without redirecting the page?

Use hash
Your website is www.example.com/page.html
Part I.
When you load page two using ajax add a hash to the url
www.example.com/page.html#page2
You can do that using javascript
window.location.hash = "page2".
Now users can bookmark www.example.com/page.html#page2
part II.
When a user request a page say, www.example.com/page.html#page2
You can read the hash using javascript.
var myHash = window.location.hash
If myHash is empty load the page normally.
If it contains "page2", then load the content of page2.

Yes, with a hash in the url. You can learn more here.
You can also find a nice jquery plugin for that purpose here.
Regards

Related

How to make "Pretty" URL after dynamic content load using ajax

I am currently developing a website that will dynamically load the page content using ajax triggered by hash changes.
The code looks like this
$("*").delegate("a", "click", function () {
// Trigger Hash Change
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function () {
let newHash = window.location.hash.substring(1);
$("#main-content").load(newHash + " #ajax-content", function (responseTxt, statusTxt, xhr) {
}).hide().fadeIn();
});
Basically what I am working on now is making the URL look "Pretty", I have modified the .htaccess file to remove the .html extension
So a URL that looks like this
www.example.com/about.html
will become this
www.example.com/about
If I navigate the index (home) "www.example.com" page of the website and then navigate from there to the about page, the URL looks fine. "www.example.com#about" since the server does not display the "index" in the URL.
However, if I navigate straight to the about page like this www.example.com/about, then from the about page to another page, for example, the contact page. I get a URL that looks like this www.example.com/about#contact. When it should look like this www.example.com#contact.
My question is what is the best way to handle this? should I use jquery to redirect all to the index page and then add the hash to load the correct content? or is there some way I can not display the unnecessary part of the URL?
I hope my question was clear, I'm new to the server-side stuff involving the .htaccess file. FOr the ajax stuff I was following this tutorial from CSS tricks
https://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/
You can use history.pushState
window.history.pushState("object or string", "Title", "/new-url");
The url will be www.example.com/new-url
in fact you can get history.state after use this method.
console.log(window.history.state)
output should be "object or string"
You can see the docs here.
Remember to use / to override the entire path.
To do what i think that you want, you can just override the url to / and set the hash.
This is probably not the best way to do this, but I have managed to redirect any page to the home page and then replace the / with the hash value so that the site wont end up wit "messy" URLs.
if(window.location.pathname != "/home.html")
{
window.location.replace("home.html" + window.location.pathname.replace("/", "#"));
}
what happens id the user navigates to "*www.example.com/about*" they will actually be sent to the homepage with the #about.html. So the never end up like this "*www.example.com/about#about*"

Add content of one page to another

Can i add the content part of this link into my webpage
http://rid3201.org/site/club_members2.php?id=MTk3Ng==
I want to avoid the header part.Can i use iframe or object for this.
Use Html Agility Pack
With it you can get the whole page and select only the html element you need (I assume it would be table).
Then you can pass it to your page.
If you own the domain rid3201.org, you can do it with jQuery:
$('#result').load('ajax/test.html #container');
heads up!
If are not the owner of the domain, you CAN'T do it via jQuery.
The documentation of .load() says:
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
An alternative to jQuery is using XMLHttpRequest, coding with a backend language, like .Net
After you catch the url source, you have to clean the code to get only the div you want.

Appcache for dynamic site

I am trying to use HTML5 Appcache to speed up my web-mobile app by caching images and css/JS files. The app is based on dynamic web pages.
As already known – when using Appcache the calling html page is always cached -> bad for dynamic websites.
My solution - Create a first static page and in this page call the manifest file (manifest="cache.appcache") and load all my cached content. Then when the user is redirected to another dynamic page the resources will already be available. (Of course this second dynamic page will not have the manifest tag).
The problem is that if the second page is refreshed by the user, the resources are not loaded from the cache; they are loaded directly from the server!
This solution is very similar to using an Iframe on the first dynamic file. I found that the Iframe solution have the exact same problem.
Is there any solution for that? Can Appcache really be used with dynamic content?
Thanks
Yes appcache can be used for dynamic content if you handle you url parameters differently.
I solved this by using local storage (I used the jquery localstorage plugin to help with this).
The process is
Internally from the page when you would normally href from an anchor or redirect, instead call a function to redirects for you. This function stores the parameters from the url to localstorage, and then only redirects to the url without the parameters.
On the receiving target page. Get the parameters from localstorage.
Redirect code
function redirectTo(url) {
if (url.indexOf('?') === -1) {
document.location = url;
} else {
var params = url.split('?')[1];
$.localStorage.set("pageparams", params);
document.location = url.split('?')[0];
};
}
Target page code
var myParams = GetPageParamsAsJson();
var page = myParams.page;
function GetPageParamsAsJson() {
return convertUrlParamsToJson($.localStorage.get('pageparams'));
}
function convertUrlParamsToJson(params) {
if (params) {
var json = '{"' + decodeURI(params).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}';
return JSON.parse(json);
}
return [];
}
I had a hell of a time figuring out how to cache dynamic pages accessed by a URI scheme like this:
domain.com/admin/page/1
domain.com/admin/page/2
domain.com/admin/page/3
Now the problem is that the appcache won't cache each individual admin/page/... unless you visit it.
What I did was use the offline page to represent these pages that you may want to allow a user to access offline.
The JS in the offline page looks up the URI and scrapes it to find out which page it should show and fetches the data from localStorage which was populated with all the page data when the user visited the admin dashboard before being presented with the links to each individual page.
I'm open to other solutions but this is all I could figure out to bring a bunch of separate pages offline with only visiting the single admin page.

Is it possible to do a url rewrite on a dynamic website?

I have done much research into the issue, I'm not blindly asking but I can't grasp this concept. So my website contains a single index.php file that loads data into divs via ajax so the page never refreshes and the url never changes. I now know I need links to certain content using url rewriting. The site contains posts, so for instance all posts are pulled from the db and 'site.com' is the url. But I want to be able to do 'site.com/post-one' and have that link go to that post. I am thinking first I need to append a variable to the end of the url when the dynamic content for that post is loaded as such: site.com?post=1 so from there I can use url rewrite; the problem I'm having is this. Since the content for post 1 would be loaded into a div, if I went this route, and implemented the url rewrite, would site.com/post-1 now just pull the data dynamically as well or does the page have to be static?
Your problem is that this would necessarily require the use of a hash, rather than a GET variable (because GET requires a page refresh, a hash doesn't). This is done via the usage of the window.location.hash variable in JavaScript, which is updated whenever the URL's content after a # changes (ex: if I were to change http://site.com/#lol to http://site.com/#lmao, window.location.hash would change from #lol to #lmao). Hashes are being used commonly in Ajax-based navigation sites, such as Twitter (I think Google's implementing it as well).
If you're using jQuery, you should try the jQuery BBQ plugin which will allow you to do things such as hash change detection (otherwise, you will have to implement some kind of similar engine yourself, because it will be needed for any kind of hash-based navigation).
You should remember, though, that this doesn't have anything to do with mod_rewrite, thus you shouldn't need to add any kind of rewrite rules. All your work (fetching data, etcetera) would be done through Ajax XML HTTP requests, rather than common HTTP requests.
Using this, you could make your url look like http://site.com/#!/post/1 (this could go whichever format you'd like, such as http://site.com/#!/p/this-is-the-posts-title) instead of http://site.com/?post=1, although you would be missing on http://site.com/post/1.
Your idea of using mod_rewrite seems sound. If you used a rewrite directive which passes part of the URI as a POST variable into your index.php, couldn't you throw some code into the top of your index file which checks for that data and then dynamically generates the ajax to dump into the divs?
Ex:
RewriteRule ^(.*)$ index.php?post=$1 [L]
Index.php:
<?php if (isset($_POST['post'])) { ?>
$.ajax({
**grab post content dump into div**
});
<?php } ?>
Also, don't forget to sanitize your $_POST data before processing it.

Calling an iframe

I created an index page with an iframe, calling srs files. The problem is that the src files are listed in Google etc. Clicking from Google on these "src" files does not load the index file, displaying the basic src file. Is there a way to overcome this?
This is a problem that was more common when a lot of sites used framesets. What you need is a script that detects if the page is opened as the main page, and redirect to the index page if it is, sending it's url along as querystring parameter:
if (window.location.href == window.top.location.href) window.top.location.href = 'index.html?url=' + escape(window.location.href);
In the index page you would have to detect the querystring that is sent to it, and load the page in the iframe:
var url = /url=(.+)/.exec(document.location.search);
if (url.length == 2) {
document.getElementById('IdOfTheIframe').src = url[1];
}
You might consider to incorporate the information in the page instead of using an iframe, that is more common nowadays. If you can't do it on the server side, you could use AJAX to load content into the page.