note 85903 added to function.urlencode
| From: | MarkSeecof at osu1 dot php dot net | Date: | Tue, 23 Sep 2008 23:34:46 +0000 |
| Subject: | note 85903 added to function.urlencode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-144656@lists.php.net to get a copy of this message | ||
When using XMLHttpRequest or another AJAX technique to submit data to a PHP script using GET (or
POST with content-type header set to 'x-www-form-urlencoded') you must urlencode your data
before you upload it. (In fact, if you don't urlencode POST data MS Internet Explorer may pop
a "syntax error" dialog when you call XMLHttpRequest.send().) But, you can't call
PHP's urlencode() function in Javascript! In fact, NO native Javascript function will
urlencode data correctly for form submission. So here is a function to do the job fairly
efficiently:
<?php /******
<script type="text/javascript" language="javascript1.6">
// PHP-compatible urlencode() for Javascript
function urlencode(s) {
s = encodeURIComponent(s);
return s.replace(/~/g,'%7E').replace(/%20/g,'+');
}
// sample usage: suppose form has text input fields for
// country, postcode, and city with id='country' and so-on.
// We'll use GET to send values of country and postcode
// to "city_lookup.php" asynchronously, then update city
// field in form with the reply (from database lookup)
function lookup_city() {
var elm_country = document.getElementById('country');
var elm_zip = document.getElementById('postcode');
var elm_city = document.getElementById('city');
var qry = '?country=' + urlencode(elm_country.value) +
'&postcode=' + urlencode(elm_zip.value);
var xhr;
try {
xhr = new XMLHttpRequest(); // recent browsers
} catch (e) {
alert('No XMLHttpRequest!');
return;
}
xhr.open('GET',('city_lookup.php'+qry),true);
xhr.onreadystatechange = function(){
if ((xhr.readyState != 4) || (xhr.status != 200)) return;
elm_city.value = xhr.responseText;
}
xhr.send(null);
}
</script>
******/ ?>
----
Server IP: 64.71.164.2
Probable Submitter: 151.152.101.44
----
Manual Page -- http://www.php.net/manual/en/function.urlencode.php
Edit -- https://master.php.net/note/edit/85903
Del: integrated -- https://master.php.net/note/delete/85903/integrated
Del: useless -- https://master.php.net/note/delete/85903/useless
Del: bad code -- https://master.php.net/note/delete/85903/bad+code
Del: spam -- https://master.php.net/note/delete/85903/spam
Del: non-english -- https://master.php.net/note/delete/85903/non-english
Del: in docs -- https://master.php.net/note/delete/85903/in+docs
Del: other reasons-- https://master.php.net/note/delete/85903
Reject -- https://master.php.net/note/reject/85903
Search -- https://master.php.net/manage/user-notes.php