marc
marc

Reputation: 3033

How send "+" sign (add, positive)

Welcome,

I'm using jquery to send form, via POST.

That's how i'm getting value.

var mytext = $("#textareaid").val();
var dataString = 'text='+ mytext;

Problem is, i lost somewhere '+' sign... PHP don't get it. But when i print mytext, i can see + sign.

I think it's special char and it's removed by jquery.

Does anyone have better idea then, repleace in javascript "+" with "hereshouldbepositivesign" and in php repleace "hereshouldbepositivesign" to "+" ? Regards

Upvotes: 1

Views: 1813

Answers (3)

aeroson
aeroson

Reputation: 1129

I had the same problem, figured out I did one more urlDecode on the data in PHP, even though PHP already did it on its own.

  • jQuery may automatically encodeURIComponent data for you if you give it data:{} as object.
  • PHP does automatically urldecode all $_POST $_GET contents.

GOOD: 1+1 => js encodeURIComponent("1+1") => 1%2B1 => php auto urldecode => 1+1

If you do one more urldecode at this point it will turn + into spaces, which you dont want.

BAD: 1+1 => js encodeURIComponent("1+1") => 1%2B1 => php auto urldecode => 1+1 => php urldecode("1+1") => 1 1

Upvotes: 0

James Curran
James Curran

Reputation: 103495

IN GET requests at least, spaces are translated into plus sign (because URLs can't have spaces), and the framework usually translates them back before giving the data to you to process.

This means you have to do something else with plus signs to get them plus signs. Normal URL encoding would make them %2B.

Upvotes: 0

Pointy
Pointy

Reputation: 413720

You have to properly encode parameter names and values:

var dataString = 'text=' + encodeURIComponent(mytext);

I didn't bother to encode "text" because it's obviously safe.

You can let jQuery do it for you if your values are in a form. You don't post how you're doing the POST, but if it's with a jQuery ajax API you can set "data" to a plain object:

{ text: mytext }

and it'll know to encode it for you.

Upvotes: 6

Related Questions