Search code examples
javascriptphphashtag

I need a hashtag value from the url in php


I need to get the text behind the hashtag in the url (http://www.example.com/#TEXT) so i can use it in a php script. I know that I have to gather the text using javascript then save it as a cookie or something like that. The only problem is that I'm not good at javascript and I have tried but failed.

How can i do this the easiest way?

Here is one thing i have tried:

<script>

var query = window.location.hash;

document.cookies = 'anchor=' + query[1];

<?php if (!$_COOKIE['anchor']) : ?>

window.location.reload();

<?php endif; ?>

<?php

echo $_COOKIE['anchor'];

?>

Solution

  • Most sites that use the fragment like this (such as Facebook) will use JavaScript AJAX calls, depending on location.hash, to send its request to the server. Try that!

    var xhr = new XMLHttpRequest();
    xhr.open("GET","something.php?hash="+location.hash.substr(1),true);
    xhr.onreadystatechange = function() {
        if( this.readyState == 4 && this.status == 200) {
            // do something with this.responseText
        }
    };
    xhr.send();