0

I have ajax calls like this at several places in my application.

$.ajax({
            type: 'POST',
            url: url,
            data: Json.stringify(Values),
            dataType: 'json'
        });

For these ones, I would like to add encodeURIComponent to data sent as below:

$.ajax({
            type: 'POST',
            url: url,
            data: encodeURIComponent(Json.stringify(Values)),
            dataType: 'json'
        });

Is there any way that I can do this globally without manually editing it everywhere?

n-dru
  • 9,285
  • 2
  • 29
  • 42
suk
  • 25
  • 8
  • 1
    jQuery parses whatever you pass as data, why would you URLencode it ? – adeneo Sep 17 '14 at 15:34
  • It's not parsing correctly when I have a "+" sign in the data. "+" is being converted to space – suk Sep 17 '14 at 15:58
  • A `+` is a space in an URL ? – adeneo Sep 17 '14 at 15:59
  • sorry, I edited the post. I too have Json.stringify applied to my data. Not sure if it's Json.stringify replacing "+" with spaces or something else. But using encodeURIComponent, I am able to retain "+" in my data on the server side. – suk Sep 17 '14 at 16:25
  • And why would you stringify, just pass the object to jQuery, and it handles the rest ? – adeneo Sep 17 '14 at 16:28
  • I needed to do as I am using a Javascript serializer on my server side code, which requires JSON string. – suk Sep 17 '14 at 16:32
  • I'm pretty sure jQuery will do that for you. – Ilia Choly Sep 17 '14 at 17:12

1 Answers1

0

Create your own function for doing it.

var myAjax = function (options) {
  if (typeof options.data !== "undefined") {
    options.data = encodeURIComponent(options.data);
  }
  return $.ajax(options);
};

Then in your code replace:

$.ajax({ type: 'POST', url: url, data: Json.stringify(Values), dataType: 'json' });

With:

myAjax({ type: 'POST', url: url, data: Json.stringify(Values), dataType: 'json' });

Whatever you do, don't monkey patch!

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160