1

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 ( '+' ) ?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

2 Comments

What do I do on the server side to get back the original data ('+') ?
@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.
3

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

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.