Lovelock
Lovelock

Reputation: 8075

Use a value after hash in the URL in PHP

i know that this isn't easily possible since the url after the # is never sent to the server.

However...

I have a page that shows 16 database results. There is a load more button which loads the next 16. I am trying to come up with a way that if the user leaves the current page, and goes back it then i can fetch the value after the hash and use that as a LIMIT claus value.

So, www.domain.com goes to www.domain.com/#1

My new results are fetched via ajax and i know you cant modify a URL with javascript without reloading the page.

Is there a way i can take the number after the # in the URL, and use it in PHP?

I dont mind a bit of hackery and getting it with javascript etc.

Thanks!

Upvotes: 0

Views: 1147

Answers (3)

Lovelock
Lovelock

Reputation: 8075

Found a way to work this.

The results are loaded each time with ajax so no page reload is needed.

I have wrapped my load more button in an A link which has a href starting off with #1.

When the new results are loaded, i change that link href to a generated pageIndex++ number.

When a user visits the page and only if the URL contains a fragment, i then convert that fragment to a ? and then redirect.

From this i can then use a PHP GET function.

Example:

// First get the page URL and split it via # signs
var parts = location.href.split('#');

// now we run a check on the URL and see how many 'parts' there are
if(parts.length > 1)
{
  var params = parts[0].split('?');
  var mark = '?';
  if(params.length > 1)
  {
    mark = '&';
  }
  location.href = parts[0] + mark + 'page=' + parts[1];
}

Upvotes: 0

Thomas
Thomas

Reputation: 8849

As you said the hash is never sent to the server. The only way to read or set the hash is using javascript.

document.location.hash.substring(1) //remove the starting hash

If you want to send it to the server you'll have to do an AJAX request. With jQuery:

$('#content').load('loadContent.php?limit='+document.location.hash.substring(1))

Upvotes: 2

Steve
Steve

Reputation: 20469

Check for the hash value on load. If exists load your ajax:

$(function(){
    if(window.location.hash){
        yourajaxfunction(window.location.hash.substr(1));
    }
});

Upvotes: 0

Related Questions