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:

1.   //from http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
2.   $.extend({
3.     getUrlVars: function(){
4.   	var vars = [], hash;
5.   	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
6.   	for(var i = 0; i < hashes.length; i++)
7.   	{
8.   	  hash = hashes[i].split('=');
9.   	  vars.push(hash[0]);
10.  	  vars[hash[0]] = hash[1];
11.  	}
12.  	return vars;
13.    },
14.    getUrlVar: function(name){
15.  	return $.getUrlVars()[name];
16.    }
17.  });

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:

1.   $(document).ready(function() {
2.   	var color = $.getUrlVar('color');
3.   	if ((color == 'blue') | (color == 'red')) {
4.   		var url = color + '.txt';
5.   		$.ajax({
6.   			url: url,
7.   		}).done(function(response) {
8.   			$('#color_display').html(response);
9.   			$('#message').html('You successfully selected a color:');
10.  		}).fail(function(jqXHR, textStatus, errorThrown) {
11.  			var message = 'Error! The Ajax call didn\'t work.<br><br>URL: ' + url;
12.  			$('#message').html(message);
13.  		});
14.  	} else {
15.  		$('#message').html('Error! An invalid color was selected.');
16.  	}
17.  });

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

1.   <!doctype html>
2.   <html lang="en">
3.   <head>
4.   	<meta charset="utf-8">
5.   	<title>Example</title>
6.   	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
7.   	<script src="geturlvars.js"></script>
8.   	<script src="example.js"></script>
9.   </head>
10.  <body>
11.  <h1>Example</h1>
12.  
13.  <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>
14.  
15.  <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>
16.  
17.  <div id="color_display"></div>
18.  
19.  <p style="margin-top:30px;">
20.  	<a href="index.html?color=red">Red</a> - 
21.  	<a href="index.html?color=blue">Blue</a>
22.  </p>
23.  
24.  </body>
25.  </html>

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.


Comments

Loading…

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.