Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blank spaces in ajax request with jquery

Tags:

jquery

ajax

I'm making an ajax request and I have some problems, this is my jquery code:

var url = "http://www.domain.com/SearchService.svc/search?keyword=my search keywords";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json".......
.....

When making this request I sometimes have blank spaces in my search (var url) and then the keywords get cutted so in the example above for example it just searches for "my". I understand this is a quite simple question and that must be an easy solution. Just couldn't find a solution...

Thanks for your help!

like image 964
Martin Avatar asked Jan 05 '10 18:01

Martin


2 Answers

You can use encodeURI:

var url = encodeURI("http://www.domain.com/SearchService.svc/search=my search keywords");

This encodes the URL and converts the blanks and any other 'unsafe' character for URL usage.

See also encodeURIComponent for safely encoding data to be inserted into a URI.

like image 54
Felix Kling Avatar answered Nov 02 '22 20:11

Felix Kling


You can escape the search keyword in the URL but the right thing to do is to add search as a parameter to the ajax request.

var url = "http://www.domain.com/SearchService.svc/search=my search keywords";
    $.ajax({
        type: "GET",
        url: url,
        data: { "search" : "my search keywords" }
        dataType: "json".......
like image 2
Pekka Avatar answered Nov 02 '22 20:11

Pekka