0

I have a textbox which has value like "PN & J".I am storing it in

var sState = $('#txtState').val();

and making Ajax call by

  data: 'Service=' + sSvendor + '&City=' + sCity + '&Sub=' + sCitySub + '&State=' + sState + '&Network=' + sNetwork,

But at the receiving end i m retrieving Value as only "PN " it is neglecting string after '&' character. how to overcome this ?

3 Answers3

3

If you concatenate the string yourself like that, you need to make sure you escape the values properly:

state = encodeURIComponent(sState)

But this will be taken care of for you if you serialize a form, or set the data to a JSON object.

data = { state: sState, ... }

or

data = $('#some-form').serialize()
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
2

Because & is the seperator of key=value pairs in a GET request, you need to escape it using encodeURIComponent;

data: 'Service=' + sSvendor + '&City=' + sCity + '&Sub=' + sCitySub + '&State=' + encodeURIComponent(sState) + '&Network=' + sNetwork,

Of note, there's also encodeURI, but that doesn't encode values like & (as it treats the input as a whole URI, rather than a particular component).

Feel free to escape the rest of the values yourself for security... I'm just too lazy.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • 1
    might be worth pointing out that you've misnamed both encode-functions in your links. – David Hedlund Sep 21 '12 at 11:34
  • @DavidHedlund: Eugh, thanks. I got it right in the code sample though, god knows what I was thinking/ typing... TGIF :P – Matt Sep 21 '12 at 11:36
1

You can use encodeURIComponent() to encode the characters.

See here for more details

Community
  • 1
  • 1
Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47