Posts Tagged ‘javascript’

jQuery and urlencode / decode


Using jQuery and ajax can be tricky if you need to get urls with parameter in them.  You need to be smart when you pass a url so make sure to encode the url.

update: August 2010

Don’t use the plugin below. It is much better to use the native javascript functions: encodeURI or decodeURI.

var uri="your url.php?name=ståle&car=saab";
document.write(encodeURI(uri)+ "
");

which outputs:

your%20url.php?name=st%C3%A5le&car=saab

For more information on this please visit:
W3schools

Comparing escape(), encodeURI(), and encodeURIComponent()

Luckily there is a function / jQuery plugin to encode url’s and decode them if you like. Download the urlencoder plugin and then use it as shown below.

1st step encode your url:

	$("#con").html(
		$.URLEncode("This is only a test");
	);

2nd step decode your url

	$("#un").html(
		$.URLDecode("This%20is%20only%20a%20test");
	);

Pretty simple. It will save you a lot of headaches, if you are doing any json or ajax.