cypher
cypher

Reputation: 6992

How to escape & in a POST request in jQuery?

i have an input element with & in value:

<input type="checkbox" value="Biografie, životopisy, osudy, Domácí rock&amp;pop" />

When i try sending it through an ajax request:

$.ajax({
    type: "POST",
    url: "/admin/kategorie/add/link.json",
    data: "id="+id+"&value="+value+"&type="+type,
    error: function(){alert('Chyba! Reloadněte prosím stránku.');}
});

the post data that actually gets sent is:

id: 1
pop:
type: e
value: Biografie, životopisy, osudy, Domácí rock

*Note that all the variables in data are defined and value contains $(thatInputElement).attr('value').

How can I escape the &amp; properly so that post field value would contain Biografie, životopisy, osudy, Domácí rock&amp;pop?

Upvotes: 9

Views: 19695

Answers (6)

Ihsan
Ihsan

Reputation: 69

you can replace & with {and} at client side, then replace {and} to & at server side

Upvotes: 0

joshtronic
joshtronic

Reputation: 381

You could create an object and pass that along instead:

vars = new Object();
vars.id = id;
vars.value = value;
vars.type = type;

$.ajax({
  type: "POST",
  url: "/admin/kategorie/add/link.json",
  data: vars,
  error: function(){ alert('Chyba! Reloadněte prosím stránku.'); }
});

Upvotes: 0

John Fisher
John Fisher

Reputation: 22719

Have you tried this syntax?

 data: {"id":id, "value": value, "type": type }

Upvotes: 2

EAMann
EAMann

Reputation: 4146

Use the HTML character code for & instead: \u0026

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

You can set your data option as an object and let jQuery do the encoding, like this:

$.ajax({
  type: "POST",
  url: "/admin/kategorie/add/link.json",
  data: { id: id, value: value, type: type },
  error: function(){ alert('Chyba! Reloadněte prosím stránku.'); }
});

You can encode each value using encodeURIComponent(), like this:

encodeURIComponent(value)

But the first option much simpler/shorter in most cases :)

Upvotes: 25

David
David

Reputation: 2795

The javascript function "escape()" should work and on the server the method HttpUtility.UrlDecode should unescape. There may be some exceptions. Additionally if you need to decode on the client, there is an equivalent "unescape()" on the client.

Upvotes: 0

Related Questions