Özer Özay
Özer Özay

Reputation: 37

How do construct a url that has an ampersand in one of the query parameter values?

I have an input, comment that contains "&". How can I use the jQuery ajax get method with this value?

For example:

index.php?comment=i&you

where the actual value of the comment field is i&you would be wrong to use as the url.

Upvotes: 4

Views: 1226

Answers (4)

mway
mway

Reputation: 4392

Use the escape() function:

var comment = 'i&you';
var url = 'index.php?comment=' + escape(comment); #=> index.php?comment=i%26you

Edit:

Missed the jQuery part, sorry. In your $.ajax() call, do:

$.ajax('index.php', {
    'data': { 'comment': 'i&you', ... }
    ...
});

By passing an object (or a string) to the data property in the options argument (documentation), you can ensure that your data is properly escaped without having to explicitly do it yourself.

Upvotes: 1

BalusC
BalusC

Reputation: 1108692

Pass parameters as a map in the 2nd argument (data).

$.get("index.php", {"comment": "i&you"});

jQuery will take care about URL encoding.

See also:


Or if those values actually come from a form, just do

$.get("index.php", $("#formid").serialize());

See also:

Upvotes: 3

tvanfosson
tvanfosson

Reputation: 532435

I would suggest using the serialize method to add data to your request. Serialize will properly encode your data for you.

$.get( 'index.php', $('form').serialize(), function(result) {
   // do something with result
});

Or if just sending one input back:

$.get( 'index.php', $('input#comment').serialize(), function(result) {
   // do something with result
});

Upvotes: 1

Chris Dixon
Chris Dixon

Reputation: 9167

I'm not too sure what you mean, but to run an AJAX call with jQuery you would do the following:

$.ajax({
  url: "index.php?comment=i&you",
  context: document.body,
  success: function(){
    // Whatever you need to do goes in this function
  }
});

Upvotes: 0

Related Questions