Wednesday, June 19, 2013

To get query string of URL in PHP and JavaScript



To get query string of a url in PHP,  we use $_GET, for example test1.php
<?php
echo htmlspecialchars($_GET["name"]);
?>

test1.php?name=jiansen&name1=andy will return jiansen
For javascript, we use document.location.search.substring
for example test2.html
<html>
      <script>        

     q=document.location.search.substring(0);
        document.write(q);
        document.write("<p>")
        q1=document.location.search.substring(1);
        document.write(q1);
       document.write("<p>")
        a=new Array();
        a=q1.split('&');
        document.write(a[0]);
    </script>
  </html>


Using test2.html?name=jiansen&name1=andy,

the following picks up the ENTIRE query string including the leading question (?) mark:

q=document.location.search.substring(0);

i.e.we got ?name=jiansen&name1=andy

To skip the question mark:
q1=document.location.search.substring(1);


i.e.we got  name=jiansen&name1=andy

Either way, then you have to parse the string:

a=new Array();
a=q1.split('&');


For first element in array, we got
name=jiansen

1 comment: