tags:

views:

21

answers:

1

Currently users can search a database using php and ajax with the results shown without a page refresh.

This requires uses to enter a search criteria - is it possible to create a direct link to the search results by including the criteria in the url?

For example:

search.php?keywords=iphone

would bring back any results for iphone without the user needing to enter a search criteria.

My ajax code is below:

function ajaxFunction(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        var ajaxDisplay = document.getElementById('ajaxDiv');
        ajaxDisplay.innerHTML = ajaxRequest.responseText;
    }
}
var kw = document.getElementById('kw').value;
var division = document.getElementById('division').value;
var queryString = "?kw=" + kw + "&division=" + division;
ajaxRequest.open("GET", "search/jsearch.php" + queryString, true);
ajaxRequest.send(null); 

}

A: 

You basically check if the url contains the keywords query string variable and if so, you call your ajax function, try this:

window.onload = function(){
    if (getQueryVariable('keywords'))
    {
        var kw = getQueryVariable('keywords');
        ajaxFunction(kw);
    }
};

You need to modify your ajaxFunction to accept an argument from url. Here is a function to get query string variable using javascript:

getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
} 
Sarfraz
That works - thank you so much.
Haribo83
@haribo83: You are welcome...
Sarfraz