Using jQuery AJAX Calls to send parameters securely

We are always providing all sorts of validations both at client and server side for security purposes. But some times a small mistake at client end during validation can pass wrong data to the server. So, there are some points that we need to keep in mind, when we pass additional parameters to the server using jQuery Ajax call.

Syntax for jQuery Ajax call: 

$.ajax({
  url: taget_page_url,
  data: param, 
  success: function(result) {
        alert('SUCCESS');
  }
});

Let’s see some examples, which will show how the way we send parameter in Ajax call going to effect our data before received by the server:

Example-1:

var type = "test&data";
var user_id = 1;
var param = 'type=' + type + '&user_id=' + user_id;
 
$.ajax({
  url: 'application/test.php',
  data: param, 
  success: function(result) {
      alert('SUCCESS');
  }
});

POST parameter in AJAX call: Parametersapplication/x-www-form-urlencoded data group_id

0

group_title

test

type

add

user_id

0

Source

type=add&group_id=0&group_title=test&data&user_id=0

Example-2:

var type = "test&data";
var user_id = 1;
var param = {type: type, user_id: user_id};
 
$.ajax({
  url: 'application/test.php',
   data: param, 
  success: function(result) {
    $('#target').html(result);
  }
});

POST parameter in AjAX call: Parametersapplication/x-www-form-urlencoded group_id

0

group_title

test&data

type

add

user_id

0

Source

type=add&group_id=0&group_title=test%26data&user_id=0

The only difference between above two examples is its way of sending parameter but it effects a lot to the parameter values, which is going to be received by server. If we will send parameter like “Example-1”, then it will not going to encode parameter as it’s already in string format. That’s why it is not going to encode those parameter. and treat value just after “&” (ampersand) as an additional parameter key.

We can also externally encode that string value using encodeURIComponent(), which is a Javascript function.

But if we will use the way(map, in key: value format) like in “Example-2”, then it will automatically encode the parameter before send to the server.

Also we can disable the option for encode parameter in Ajax call by set “processData” option in Ajax setting to “false”(default “true”).

Reference:
http://api.jquery.com/jQuery.ajax/

150 150 Burnignorance | Where Minds Meet And Sparks Fly!