Home > javascript, jQuery > A mistake to avoid when calling jQuery.ajax

A mistake to avoid when calling jQuery.ajax

I can’t think of a reason why jQuery.ajax accepts both object and query string as the valid format the data parameter, for example,

$.ajax( {
    data: { key1: val1, key2: val2 },
    // alternatively, the following format is also accepted
    // data: 'key1='+val1+'&key2='+val2,
    success: function() {
} );

In the above example, the query string format is also accepted but should be discouraged to use, reason of which will be demonstrated with the following example. We need to submit data in the text fields as is to the server. When query string format is used, data is passed to the server without being encoded properly, as you can see from the first screenshot. For demonstration purpose, password field uses “text” as its input type.


<title>Rico's Appbox Demos | A mistake to avoid when using jQuery.ajax() function</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script type="text/javascript">
	function do_post( data ) {
		var io='Sent from client:\nusername: '+$('#username').val()+'\npassword='+$('#password').val();
		$.ajax( {
			url: '/demos/jpost',
			data: data,
			success: function(d) {
				io+='\n\nReceived by server:\n'+d
		return false;

        function post_qs() {

	function post_json() {
			username: $('#username').val(),
			password: $('#password').val()


	Username: <input id="username" type="text" value="This?is+ok">
	Password: <input id="password" type="text" value="asdf%20test">
	<a href="#" onclick="post_qs()">Post via query string format (BAD)</a><br />
	<a href="#" onclick="post_json()">Post via json format (GOOD)</a> 


Live demo is available at http://ricosappbox.appspot.com/demos/jpost.
The screenshots below are slightly different to the live demo result because they were created when I used php as the back-end to print the post data.

When first link (using query string format) is clicked:

When the second link (using json format) is clicked:

Categories: javascript, jQuery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: