-2

I'm making a custom search for my website, the search result are link to other pages along with specific id (div id=""), so that can navigate that div to top of web page. I can not simply use something like www.mysite.com/faq.php#divid , since I have to also pass(using$_GET variable) some variables also to highlight search text on the target webpage. Is there any way that I can pass search highlighting values and navigate that div to the top of page. I cannot use SESSION varible also, since the search result will have number of different results.

my link will be likehttp://www.example.com/faq.php?keyword=somekeyword&divid=q6

  • You can retrieve [query string values via JavaScript](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript), and then use them for highlighting and manipulating the div. – Cᴏʀʏ Sep 16 '15 at 12:43

2 Answers2

0

Simply use some JS:

function parseUrl(key) {
    /**
     * returns the value of the GET-parameter with key 'key'
     */
    var result,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
            tmp = item.split("=");
            if (tmp[0] === key) result = decodeURIComponent(tmp[1]);
        });
    return result;
}
Alex
  • 799
  • 5
  • 15
  • Thanks a lot for such a quick replay, Unfortunately my problem is not just retrieving the values form get variable(I had done with some php and json_encode, but now i will use this) , but how I can navigate my webpage such that the specific div can be brought to the top of page. for example, if id is "q6", then some thing like www.example.com/faq.php#q6 might have done. Since i'm using get method to pass values, I can not do that way. Is there a way in javascript that after getting the id value from GET variable, the id brought to the top of the page?. Sorry 4 asking such a simple question :( – Ashfaque Ahammed Sep 16 '15 at 13:39
  • 1
    Oh, thats another thing. If you are using jQuery (which you definetely should do) you can use `$.scroll()` together with `$(element).offset()` – Alex Sep 16 '15 at 13:47
0

I agree with Alex and Cory that you could easily use JS (see another function here: JS get variables from URL)

But let me add that another alternative is to use server-side (php) to process the GET variables and pass the div's id to JS. (no SESSION vars are needed) Something like:

<?php
// TOP OF PAGE
$divid=NULL;
if (isset($_GET["divid"])) {
    $divid=$_GET["divid"];
}
?>
<!-- HTML STARTS HERE -->

Then, in the <head>:

<script>
var divid="<?php echo $divid; ?>";

if (divid.length >0) {
    // do something with divid
}
</script>

But JS it's prettier... :)

Community
  • 1
  • 1
verjas
  • 1,793
  • 1
  • 15
  • 18