27

Currently, everywhere I use serialize I have to use it like this:

.serialize().replace(/\+/g,'%20');

otherwise any spaces in the form data will be coverted to +'s. Is there a setting that can make this the default.

Severin
  • 8,508
  • 14
  • 68
  • 117
Mark Steggles
  • 5,369
  • 8
  • 40
  • 50

3 Answers3

4

For fun, here's an alternative that doesn't use a temporary variable:

$.fn.serializeAndEncode = function() {
    return $.map(this.serializeArray(), function(val) {
        return [val.name, encodeURIComponent(val.value)].join('=');
    }).join('&');
};

$("#formToSerialize").serializeAndEncode();
russianmario
  • 690
  • 5
  • 14
1

I had to do the same thing. The solution Terry gave, with escape(), doesn't work. The = and & are getting encoded (we don't want that) and the + are still there.

What I did is creating my own function to serialize:

var QueryString = "";
$(selector).each(function(index) {
    if(QueryString != "") QueryString += "&";
    QueryString += $(this).get(0).id + "=" + encodeURIComponent( $(this).val() );
});
Matt Roy
  • 1,455
  • 1
  • 17
  • 27
-1

Don't believe there is a default, you will need to encode the string in one of these ways.

Though you could create your own plugin:

jQuery.fn.serializeAndEncode = function() {
    return escape(this.serialize());
}

$(myForm).serializeAndEncode();
Terry
  • 14,099
  • 9
  • 56
  • 84
  • 2
    Please don't use `escape`. It has been [deprecated for many years](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#escape_and_unescape_functions(Obsoleted_above_JavaScript_1.5) and should be replaced with `encodeURIComponent` like in Matt Roy's example. – Husky Jun 04 '14 at 15:04