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( {
    url:'/someurl',
    type:'POST',
    data: { key1: val1, key2: val2 },
    // alternatively, the following format is also accepted
    // data: 'key1='+val1+'&key2='+val2,
    success: function() {
        alert(d);
    }
} );

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.

index.html

<html>
<head>
<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',
			type:'POST',
			data: data,
			success: function(d) {
				io+='\n\nReceived by server:\n'+d
				alert(io);
			}
		});
		return false;
	}

        function post_qs() {
		do_post('username='+$('#username').val()+'&password='+$('#password').val());
	}

	function post_json() {
		do_post({
			username: $('#username').val(),
			password: $('#password').val()
		});
	}
</script>

</head>
<body>

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

</body>
</html>

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.

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

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

Advertisements
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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: