views:

51

answers:

3

Was experimenting with some basic http post stuff with php and ran into this problem.

1.php:

<head>
    <script src="/scripts/jquery.js"></script>
</head>
<body>

    <script>
        function hw(){
            $.ajax({
              type: 'POST',
              url: '/2.php',
              data: 'param=a+b+c',
              success: function(d){
                console.log('server said ' + d);
              }
            });

        }
    </script>
    <button onclick="javascript:hw();">CLick me</button>
</body>

2.php:

<?php
echo $_POST['param'];
?>

the ajax call returns with 'a b c' instead of 'a+b+c'. Why is it that '+' is encoded to a ' '(space) ?

I then tried using the content type of the post request as 'text/plain' instead of the default 'application/x-www-form-urlencoded'. In this case, $_POST['param'] comes out to be empty ? I want to understand what exactly is going on in both these cases. What do I do on the server side to get back the original data ( '+' ) ?

+5  A: 

Content type has nothing to do with the URL query containing + because that symbol is the URL-encoded equivalent of a space per RFC 1738. Use %2B as a library-agnostic alternative.

stillstanding
What do I do on the server side to get back the original data ('+') ?
letronje
urldecode() or rawurldecode()
stillstanding
@letronje: You should be encoding your data in JavaScript as well to prevent those problems. jQuery can handle this for you. SeniorDev posted how to do that. Decoding on server-side is not needed, since PHP handles this for you.
elusive
+4  A: 

Use

data: 'param='+encodeURIComponent('a+b+c') 

instead o f

data: 'param=a+b+c'

and you will be able to use the data normally without decoding.

Joyce Babu
+5  A: 

Use data: {param: 'a+b+c'}

SeniorDev
Since he is using jQuery, this is the easiest and cleanest solution! +1!
elusive
why does this work ? jquery uses encodeURIComponent internally ?
letronje
@letronje I checked jquery source, and found: s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
SeniorDev