251

I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a +, thus breaking the search. How can I either replace the space with a +, or just safely URL Encode the string?

$("#search").keypress(function(){       
    var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val();
    var options = {};
    $("#results").html(ajax_load).load(query);
});
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
Brian D
  • 9,863
  • 18
  • 61
  • 96

6 Answers6

543

Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:

var encoded = encodeURIComponent(str);
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Anders Fjeldstad
  • 10,724
  • 2
  • 33
  • 50
  • 2
    This solved my problem - when I was passing in a URL as a parameter to my AJAX request, the URL was losing everything after the & for any query strings in it. When I added this, that solved my problem. Thanks! – theJerm Aug 18 '14 at 19:00
26

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:

  $.ajax({
    cache: false,
    type: "POST",
    url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Praveen04
  • 985
  • 10
  • 12
10

Better way:

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.

For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".

If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
StackOverFlow
  • 4,486
  • 12
  • 52
  • 87
  • 1
    `For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".` How does one do this? – secondman Jul 30 '13 at 20:08
  • 1
    but for this to be useful there would need to be a urldecode equivalent – Mr Heelis Jun 07 '18 at 09:41
5

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)

Hardcoded URL i.e.>

 var encodedName = encodeURIComponent(name);
 var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;

Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method

 var url = "ControllerName/ActionName/";   
 $.post(url,
        { name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
 function (data) {.......});
d1jhoni1b
  • 7,497
  • 1
  • 51
  • 37
1

use jQuery.param().....
Description: Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.

Aftershock
  • 5,205
  • 4
  • 51
  • 64
0

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');
genesis
  • 50,477
  • 20
  • 96
  • 125
  • 5
    Anders Fjeldstad's solution is far better. Replacing spaces with plus signs may work, but if you have other characters (with umlauts etc), you are going to be in heap of trouble. – Uku Loskit Jul 01 '11 at 07:06
  • 1
    @Uku: OP wanted to replace whitespace with + so I given him answer how to do it. encodeURIComponent gives him %20 – genesis Jul 01 '11 at 07:07
  • 2
    I think @Uku is right. While this does answer the literal question (and it definitely works), I think @Anders's solution is better in the bigger scheme of things. – Brian D Jul 01 '11 at 07:09