views:

541

answers:

3

I want to send a URL in a POST request in a variable called surl. How should I encode it in JavaScript and decode it in PHP? For example, the value of surl could be http://www.google.co.in/search?q=javascript+urlencode+w3schools.

EDIT

Sorry, I forgot to mention, it's not form submission but a ajax request.

+2  A: 

You don't need to to anything. Send it as is. Browser and PHP will do all escaping and unescaping for you (if you use form.surl.value = surl; form.submit() and $_POST['surl']). Or you can just use the plain form without any JavaScript (if it fulfills your needs).

Replying henasraf's comment. Try this.

<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"
    onsubmit="this.via_js.value=this.via_plain_form.value;">
<input type="hidden" name="via_js"/>
<input type="text" name="via_plain_form" value="Paste you url here"/>
<input type="submit" name="submit" value="Submit"/>
</form>

<?php

if (isset($_POST['submit'])) {
    var_export($_POST);
}

?>

For http://www.google.co.in/search?q=javascript+urlencode+w3schools, it outputs

array (
    'via_js' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
    'via_plain_form' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
    'submit' => 'Submit',
)
codeholic
Correct me if I'm wrong, but + in the URL would count as space, no? PHP wouldn't fix it I'm sure, it *will* fix regular spaces and turn them to "+" signs and vice-versa, but to add a literal + you'd have to use `%2B`. I think this applies in other cases too.
henasraf
PHP or browser don't care if you transmit URL or something else. URL is treated like any other form data. Browser escapes all fancy characters in your form data, transmits data, and PHP unescapes them on the other end.
codeholic
+1  A: 

Use encodeURIComponent(uri) (for encoding) and decodeURIComponent(uri) for decoding,

E.g (encoding).

var uri="http://w3schools.com/my test.asp?name=ståle&car=saab";
document.write(encodeURIComponent(uri));

Output

http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab

Decoding is left for the reader. :-)

Source: http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp

The Elite Gentleman
A: 

As for PHP, it's urlencode() and urldecode().

henasraf