views:

66

answers:

4

I'm collecting text through a web form and noticing that when it is collected by my Perl CGI all instances of "+" are transformed into " ". I run the text through a JavaScript escape before submission, but escape seems to leave + unaltered.

There must be something really obvious that I'm missing... how do I send the string "2 + 2 = 4" through and not have it arrive as "2 2 = 4"?

+4  A: 

The escape and unescape functions do not work properly for non-ASCII characters and have been deprecated. In JavaScript 1.5 and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Predefined_Functions/escape_and_unescape_Functions

Replace escape with encodeURIComponent

David Dorward
+1  A: 

You can encode + as %2B, as seen in: http://www.google.com/search?q=2+%2B+2

Callahad
+3  A: 

You '+', in the URL, should be encoded as %2B :

http://www.example.com/myscript.ext?a=2%20%2B%202%20=%204

Will give a = 2 + 2 = 4


In Javascript, this means using the encodeURIComponent function : this portion of code :

encodeURIComponent('2 + 2 = 4')

will give :

"2%20%2B%202%20%3D%204"

Note the + is encoded.


While this one :

escape('2 + 2 = 4')

would only give :

"2%20+%202%20%3D%204"

Note the + is not encoded.

Pascal MARTIN
+1  A: 

I do not know what you mean by using JavaScript escape. Browsers will properly encode form field values and CGI.pm will properly decode them.

For example,

#!/usr/bin/perl

use strict; use warnings;
use CGI;

my $cgi = CGI->new;

if ( $cgi->param ) {
    process_form($cgi);
}
else {
    show_form($cgi);
}

sub process_form {
    my ($cgi) = @_;

    print $cgi->header('text/plain'),
          $cgi->param('entry'), "\n";
}
sub show_form {
    my ($cgi) = @_;

    print $cgi->header, <<EO_HTML;
<!DOCTYPE HTML>
<html><head><title>Test +</title></head>
<body><form>
<input name="entry"><input type="submit">
</form></body></html>
EO_HTML
}

The output I get from submitting this form with 2+2=4 in the entry field is:

2+2=4
Sinan Ünür
I'm using ajax so the form never gets to submit its values natively. However the above two answers do the trick.
Dr.Dredel
Uh, AJAX form submissions are no different than regular form submissions.
jrockway
@Dr. That makes no sense at all but whatever rocks your boat.
Sinan Ünür
what i mean is that I submit the values via an AJAX post, not from the form. When the values arrive they are not encoded or escaped in any way. If there is any kind of encoding happening behind the scenes it has been unencoded by the time the CGI.pm module is done collecting the params.
Dr.Dredel