Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Do I need to URL encode a variable?

I am using ColdFusion 9 and the latest and greatest jQuery.

At the top of my page, I use this:

<cfajaxproxy cfc="artists" jsclassname="jsApp">

I have a search field:

<input id="Artist" class="Search" type="text">

When a user types in the search field, the value is passed into a jQuery function:

$(".Search").keyup(function() {
  var Artist = $("#Artist").val();
  var QString = "Artist=" + Artist;
  $("#ArtistSearchResultsDiv").load("ArtistSearchResults.cfm?"+QString);
});

The search results div loads a page with these items in CFSCRIPT:

objArtists = createObject("component", "artists");
GetArtists = objArtists.getArtists(Artist);

I have a CFC that runs the query and returns the correct records.

The PROBLEM is that when I type in the search box, as soon as I hit a space, no further value is added to the QString variable, and so those values aren't passed to the query.

Here's how much search string looks in Firebug when searching for "The Beatles":

GET http://127.0.0.1:8500/WebSites/AwesomeAlbums/GlobalAdmin/ArtistSearchResults.cfm?Artist=The

It's stops as soon as it sees a space.

So, if you were searching for "The Beatles", only the value "The" would be passed into the QString variable. If you were searching for "Celine Dion", only "Celine" would be passed.

I am assuming that I need to URL encode the QString somehow. Is that correct? How do I do that?

like image 733
Evik James Avatar asked Sep 19 '11 21:09

Evik James


People also ask

Is URL encoding necessary?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.

Should I URL encode post data?

General Answer. The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers. A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string.

What is the purpose of encoding URL?

URL encoding converts characters into a format that can be transmitted over the Internet. URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format.

How do you escape a parameter in a URL?

URL escape codes for characters that must be escaped lists the characters that must be escaped in URLs. If you must escape a character in a string literal, you must use the dollar sign ($) instead of percent (%); for example, use query=title%20EQ%20"$3CMy title$3E" instead of query=title%20EQ%20'%3CMy title%3E' .


1 Answers

var QString = "Artist=" + encodeURIComponent(Artist);
like image 159
Matteo Riva Avatar answered Sep 30 '22 20:09

Matteo Riva