views:

38

answers:

1

I'm reading the value of an input text field and passing it to be used as ajax data

The field value has a +

<input name="someval" type="text" value="Receive (+ open)" />

and looks like when parsed with data, it parses the + as a jquery concatenation.

data: 'someval=' + $("input[name=someval]").val(),

This is the first time I notice this behavior.

  • First, how do I solve it.
  • Second, I have no way of knowing when the output might have these special chars, so is there a known best practice way to escape input so that whenever it happens we're covered?

Thanks

+2  A: 

Try encodeURIComponent:

'someval=' + encodeURIComponent($("input[name=someval]").val())

Better yet, let jQuery handle it for you:

data: { someval:$("input[name=someval]").val() }

jQuery will automatically escape your values (and keys) into the correct format (using jQuery.param()) for the data type (eg "application/x-www-form-urlencoded").

Roatin Marth
So I guess every time it's possible that the input could contain special chars, I have to use this. Is this how it's done.
Chris
@Chris: see my update.
Roatin Marth
Pretty good stuff Roatin, thanks so much
Chris
Chris, see my update to your other post at http://stackoverflow.com/questions/1683198/jquery-ajax-response-removes-the-character/1683641#1683641
Phil Derksen