views:

94

answers:

5

Hi, 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?

A: 

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.

David
Actually you're better off with "encodeURIComponent"
Pointy
+5  A: 

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 :)

Nick Craver
Thank you, this with encodeURIComponent did the trick, I assume i can decode it on the server-side (PHP) using urldecode($var)?
cypher
@cypher - It should be automatically decoded, but it's been forever since a PHP application so double check me on that.
Nick Craver
A: 

Use the HTML character code for & instead: \u0026

EAMann
See this related post for reference: http://stackoverflow.com/questions/355043/how-do-i-escape-an-ampersand-in-a-javascript-string-so-that-the-page-will-validat
EAMann
+2  A: 

Have you tried this syntax?

 data: {"id":id, "value": value, "type": type }
John Fisher
A: 

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.'); }
});
joshtronic