Chapter 34. Making Ajax Requests Using POST

If GET requests make up the majority of HTTP requests on the Web, POST requests come in second. POST requests are typically generated by forms. While not every form sends its data using the POST method, many are used to POST information to the server.

POST requests are the exact opposite of GET requests: They are used to submit data to a web application so the application can do something with that data. The request's data is sent in the request's body, unlike with GET requests, in which data can be sent in the URL's query string. Despite these differences, making POST requests with XMLHttpRequest (XHR) objects is strikingly similar to making GET requests. There are, of course, some differences, and you'll learn about them in this lesson.

ASSEMBLING DATA

POST requests are designed to send information from the browser to the server. Because of this the majority of POST requests are made through forms. Forms are the primary means by which users input and send data. The difference with Ajax, however, is in how that data is sent.

Without Ajax, the browser is responsible for gathering the form's data, formatting it, and POSTing it to the server. With Ajax, that responsibility falls to you. So before sending a POST request you must assemble the form's data and format it.

Let's look at an example form:

<form name="theForm" method="post" action="ajax_test.php"> <p> Name: <input type="text" name="txtName" value="" /> </p> <p> Email: <input type="text" ...

Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.