Information Technology Reference
In-Depth Information
POST vs. GET
You'll notice that in our examples, we're consistently using the GET method versus the
POST method, as first seen in Listings 12-3 and 12-4. The reason for this, primarily, is
speed. GET is much faster than POST because of the simpler format it uses. If you're
wondering why, it's most likely due to the original intent of GET—it was designed to be
for “idempotent” data only. This simply means that the information isn'tmeant for lasting
use (i.e., itshould simply be a lookup value, not data to be entered into a database or
processed in any way).
However, there are times when POST will be appropriate. First, POST doesn't have the
size limitations that GET does, so if you're passing a lot of information to the server,
you'll need to use POST. Second, POST should be used whenever you're changing
something on the server (such as a database update), versus referencing static or
cached content. Simply put, use GET if you're passing data that won't be needed again.
Use POST if you're passing data that should be processed or entered into a database,
e-mail, or file.
Using POST is slightly more complex than GET. You'll need to set a request header, and
send information through the send function. This is because POST data are encoded in a
message body, whereas GET data are simply tacked onto the URL. This is why the
Android browser in Figure 12-8 mentions resending POSTDATA—it's referring to this
specially encoded message. If we wanted to changeour username example to use
POST, we could change the following lines:
request.open("GET","check_name.php?u=" + $name,true);
request.send();
The change would result in the lines shown in Listing 12-9.
Listing 12-9. Using POST in the Username Availability Example
request.open("POST","check_name.php",true);
request.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);
request.send(“u=”+$name);
We would also have to alter the PHP script (see Listing 12-7), changing the first line from
$name = $_GET['u']; to $name = $_POST['u'];
Setting Asynchronous to False?
As you've seen from the preceding examples, the third argument of the open function for
our XMLHttpRequest is normally set to “true.” It makes sense this way—after all, why
would we want to set it to false anyway? Well, the answer is that there are very few
times we would! Still, in some circumstances you might. For example, if you're writing a
script and you absolutely do not want something to happen until the request is returned
and ready for processing, it would be permissible to set this to false. An example that
comes to mind involves a username check form, similar to the one in Figure 12-16, that
should only allow the user to continue with the form if the username is available (perhaps
 
Search WWH ::




Custom Search