« Get query string with JS | Main | RSS 1.0 Job Vacancy Schema »

May 29, 2009

Getting GET parameters with JavaScript and setting them in a cookie

var queryString = window.top.location.search.substring(1);

function getParameter ( queryString, parameterName ) {

	// Add "=" to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + "=";

	if ( queryString.length > 0 ) {

		// Find the beginning of the string
		begin = queryString.indexOf ( parameterName );

		// If the parameter name is not found, skip it, otherwise return the value
		if ( begin != -1 ) {

			// Add the length (integer) to the beginning
			begin += parameterName.length;

			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf ( "&" , begin );

			if ( end == -1 ) {

				end = queryString.length

				}

			// Return the string
			return unescape ( queryString.substring ( begin, end ) );

			}

		// Return "null" if no parameter has been found
		return false;
		
		}
	}

function get_start_date(queryString){

	var start_date = getParameter(queryString, 'SQ_CALENDAR_DATE')

	if(start_date){ return start_date; }

	return false;

	}


function get_view(queryString){

	var view = getParameter(queryString, 'SQ_CALENDAR_VIEW')

	if(view){ return view; }

	return false;

	}

function create_cookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
        
        }

function read_cookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0){   
                
                    //alert(c.substring(nameEQ.length,c.length));
                
                    return c.substring(nameEQ.length,c.length);
	
                    }
        
        }
	return false;
        }


//If we don't have a start date in the URL, try getting the cookie and if we have one redirect back to ourselves including the start_date in the URL

if(get_start_date(queryString) == false){

        var bicky = read_cookie('start_date');

        if(bicky != false){ document.location.href = document.location.href + '?SQ_CALENDAR_DATE=' + bicky; }

        }

//Otherwise we have a start date in the URL query so grab it and slot it into a cookie

else{ create_cookie('start_date', get_start_date(queryString), 1); }

//If we have called a day view then redirect us to the day view asset

if(get_view(queryString) == 'day'){ document.location = 'day'; }

if(get_view(queryString) == 'week'){ document.location = 'week'; }

if(get_view(queryString) == 'month'){ document.location = 'month'; }

//alert(read_cookie('start_date'));

Tags: JavaScript

Posted by pj at May 29, 2009 09:54 PM

Comments