Javascript Add Query String Parameter - Code-Tips.com - Web Development, Programming, SEO

Sunday, February 13, 2011

Javascript Add Query String Parameter

Redirect to the current page including the specified query string parameter and value
This Javascript function redirects the browser back to the current page with the query string parameter data included that is passed to the function.  If the current url already contains the supplied query string and value, no redirect will take place.  Existing parameters and values are retained in the url after the redirect.

This function can be useful when a common query string parameter is required across multiple pages on a site, such as a session hash/id or similar.  
The current page will reload to include the specified parameter and value if it doesn't already exist.  Use this function in combination with the updateLinks() function to add and manage query string parameters and variables across pages on a site dynamically.


function addParameter(parameter, value)
{
   //Get Query String from url
   fullQString = window.location.search.substring(1);
   
   paramCount = 0;
   queryStringComplete = "?";

   if(fullQString.length > 0)
   {
       //Split Query String into separate parameters
       paramArray = fullQString.split("&");
       
       //Loop through params, check if parameter exists.  
       for (i=0;i<paramArray.length;i++)
       {
         currentParameter = paramArray[i].split("=");
         if(currentParameter[0] == parameter) //Parameter already exists in current url
         {
            //don't include existing (will be appended to end of url)
         }
         else //Existing unrelated parameter
         {
            if(paramCount > 0)
               queryStringComplete = queryStringComplete + "&";
           
            queryStringComplete = queryStringComplete + paramArray[i];
            paramCount++;
         }
       }
   }
   
   //Add/Update query string if required.
   if(paramCount == 0)
       queryStringComplete = queryStringComplete + parameter + "=" + value;
   else
       queryStringComplete = queryStringComplete + "&" + parameter + "=" + value;
   
   window.location = self.location.protocol + '//' + self.location.host + self.location.pathname + queryStringComplete;
   
   
}


Next: Javascript Check if Query String Parameter Exists in current URL

Javascript Query String Manipulation (TOC)

1 comment: