test
test

Reputation: 18198

Make usable URLs during request

I'm doing an ajax request through jQuery and for example, my URL is http://test.com/query.php?hello=foo bar

However, the request only takes http://test.com/query.php?hello=foo. How do I make it so it takes even spaces? And special character entities like &, -, !, etc.

Thanks

Upvotes: 0

Views: 41

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039050

How do I make it so it takes even spaces?

By properly url encoding the space:

http://test.com/query.php?hello=foo+bar

or:

http://test.com/query.php?hello=foo%20bar

And special character entities like &, -, !, etc.

It's the same. Make sure you url encode them properly:

  • & => %26
  • - => - (doesn't need to be encoded)
  • ! => ! (doesn't need to be encoded)

In order to properly do this in javascript you could use the encodeURIComponent function.

Or if you use jQuery you could also take a look at the $.param() method.

Finally if you are sending an AJAX request using jQuery you could do this:

$.ajax({
    url: 'query.php',
    type: 'GET',
    data: { hello: 'foo bar' },
    success: function(result) {
        ...
    }
});

and jQuery will take care of properly url encoding the query string parameter passed in the data hash.

Upvotes: 2

Parv Sharma
Parv Sharma

Reputation: 12705

you can do an encodeURI(URI)
visit this link for more info https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI

Upvotes: 0

Related Questions