1

I am creating a website updater. I am passing strings over CGI using AJAX.

I have a problem where if my strings contain an '&' character they get incorrectly separated because CGI separates parameters/variables by a '&' character

So if I send this:

http://mywebsite.com?user=blah&mystring=I_am_happy_&_sad

When I get the variables in my python script the variable mystring will be incorrect:

input_data   = cgi.FieldStorage()
user         = input_data.getvalue( "user" ) # correctly = "blah"
mystring     = input_data.getvalue( "mystring" ) # incorectly = "I am happy "
# mystring should = "I am happy & sad"

Now I am using my own post() function in Javascript to send AJAX requests, so I dont use jQuery or anything. Is there a simple way to send strings over CGI that contain '&' in it or will I need to write my own function to parse the string & replace the '&' chars with something else?

user593747
  • 1,484
  • 4
  • 32
  • 52

1 Answers1

4

You need to URL-encode the ampersand character:

http://mywebsite.com?user=blah&mystring=I_am_happy_%26_sad

To do that, Javascript provides encodeURIComponent() and Python provides urllib.quote().

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479