AJAX - The Complete Reference

(avery) #1

Chapter 3: XMLHttpRequest Object 81


PART I


{
var url = "http://ajaxref.com/ch3/setrating.php";
var payload = "rating=" + encodeValue(rating);

sendRequest(url, payload);
}
window.onload = function ()
{
var radios = document.getElementsByName("rating");
for (var i = 0; i < radios.length; i++)
{
radios[i].onclick = function (){rate(this.value);};
}
};

</script>
</head>
<body>
<h3>How do you feel about Ajax?</h3>
<form action="#" method="get">
<em>Hate It - </em> [
<input type="radio" name="rating" value="1" /> 1
<input type="radio" name="rating" value="2" /> 2
<input type="radio" name="rating" value="3" /> 3
<input type="radio" name="rating" value="4" /> 4
<input type="radio" name="rating" value="5" /> 5
] <em> - Love It</em>
</form>
<br />
<div id="responseOutput"> </div>
</body>
</html>

Sending Data via Post


Sending data via an HTTP POST request is not much more difficult than the GET example—
a welcome change from the iframe examples of the previous chapter. First, change the call
to open() to use the POST method.

xhr.open("POST",url,true);

Next, if you are sending any data to the server, make sure to set a header indicating the
type of encoding to be used. In most cases, this will be the standard x-www-form-urlencoded
format used by Web browsers doing form posts.

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

A common mistake is to omit this header, so be careful to always add it with the
appropriate encoding value when transmitting data via POST.
Free download pdf