Load a Variable File Based on Query String with jQuery and Ajax

Including files with PHP based on a query string is easy. But if you find yourself in a situation where you can only use client-side languages, it gets a little trickier. I ran into this problem on a recent project and came up with the following. I hope it helps you out.

First, check out the example to see what we're doing.

As you can see, a red box or blue box is displayed, depending on your query string. Nothing too fancy. But, what's cool is that there's no server-side logic involved. Here's how it works…

First, you have to grab the variables from the query string using jQuery/JavaScript. For that, I grabbed a function from this blog post and saved it as geturlvars.js:

//from http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
      hash = hashes[i].split('=');
      vars[hash[0]] = hash[1];
    return vars;
  getUrlVar: function(name){
    return $.getUrlVars()[name];

Once that's done, the rest is really simple. You just match the variables to the include files you want to use. That's found in example.js:

$(document).ready(function() {
	var color = $.getUrlVar('color');
	if ((color == 'blue') | (color == 'red')) {
		var url = color + '.txt';
			url: url,
		}).done(function(response) {
			$('#message').html('You successfully selected a color:');
		}).fail(function(jqXHR, textStatus, errorThrown) {
			var message = 'Error! The Ajax call didn\'t work.<br><br>URL: ' + url;
	} else {
		$('#message').html('Error! An invalid color was selected.');

With both of those scripts in place, all that's left is the HTML itself:

<!doctype html>
<html lang="en">
	<meta charset="utf-8">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	<script src="geturlvars.js"></script>
	<script src="example.js"></script>

<p>This example is a supplement to the <a href="https://inkplant.com/code/query-string-ajax">Load a Variable File Based on Query String with jQuery and Ajax</a> article on the Ink Plant Code blog.</p>

<p id="message">Error! This message should have been replaced with something else. The fact that you're reading this means something went wrong with the JavaScript.</p>

<div id="color_display"></div>

<p style="margin-top:30px;">
	<a href="index.html?color=red">Red</a> - 
	<a href="index.html?color=blue">Blue</a>


You have to make the include files too (red.txt and blue.txt) of course. I saved them as .txt files, but they can be saved as .html instead if you prefer.

That wraps it up. Super easy.



This post was published on November 23rd, 2015 by Robert James Reese in the following categories: Ajax, JavaScript, and jQuery Before using any of the code or other content in this post, you must read and agree to our terms of use.