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-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);
}
******/?>