Question

Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.

My address bar currently looks like this:

http://localhost/social3/browse/?locationName=Cambridge

Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:

$searchResult = $_POST['locationName'];
echo $searchResult;

But because I'm in an Ajax div, I can't seem to get to the variable.

Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)

My Ajax:

<script>    
window.onload = function () {
    var everyone = document.getElementById('everyone'),
        searching = document.getElementById('searching'),
        searchingSubmit = document.getElementById('searchingSubmit');

    everyone.onclick = function() {
        loadXMLDoc('indexEveryone');
        everyone.className = 'filterOptionActive';
        searching.className = 'filterOption';
    }

    searching.onclick = function() {
        loadXMLDoc('indexSearching');        
        searching.className = 'filterOptionActive';
        everyone.className = 'filterOption';
    }

     searchingSubmit.onclick = function() {
        loadXMLDoc('indexSearchingSubmit');  
    }

    function loadXMLDoc(pageName)
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
            }
          }

        function get_query(){
          var url = location.href;
          var qs = url.substring(url.indexOf('?') + 1).split('&');
          for(var i = 0, result = {}; i < qs.length; i++){
            qs[i] = qs[i].split('=');
            result[qs[i][0]] = decodeURIComponent(qs[i][1]);
          }
          return result;
        }

        xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
        xmlhttp.send();
        }
}
</script>
<!-- ends ajax script -->
Was it helpful?

Solution

If your url contains the variable, you should use $_GET["key"] instead of $_POST

alternatively, you can use $_REQUEST["key"] to handle both cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top