URL Encode a string in jQuery for an AJAX request

Brian D picture Brian D · Jul 1, 2011 · Viewed 427.1k times · Source

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);
});

Answer

Anders Fjeldstad picture Anders Fjeldstad · Jul 1, 2011

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