How to Make GET, POST, and HEAD Requests Using Ajax

  • google plus

In Brief...

Although the HTTP specification identifies several methods of HTTP requests, the most commonly supported (and used) methods are GET, POST, and HEAD.

Instructions

The HEAD Method

The HEAD method is the least commonly used of the three. Its purpose is to return the meta-information contained in the HTTP headers. To make a HEAD request, follow these two steps:

  1. Create a call to the open() method and pass in "HEAD" as the first argument and a URL as the second argument.
    xmlhttp.open("HEAD","http://www.example.com/Demo");
  2. Send the request.
    xmlhttp.send();

The GET Method

The GET method is used to send information to the server as part of the URL. To make a GET request, follow these two steps:

  1. Create a call to the open() method and pass in "GET" as the first argument and a URL, with name-value pairs passed as a querystring, as the second argument.
    xmlhttp.open("HEAD","http://www.example.com/Demo?FirstName=Chris&LastName=Minnick");
  2. Send the request.
    xmlhttp.send();

The POST Method

The POST method is used to send information as an enclosed entity. To make a POST request, follow these three steps:

  1. Create a call to the open() method and pass in "POST" as the first argument and a URL as the second argument.
    xmlhttp.open("POST","http://www.example.com/Demo");
  2. Set the content type to "application/x-www-form-urlencoded;charset=UTF-8");
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
  3. Send the request, passing in name-value pairs through the send() method.
    xmlhttp.send("FirstName=Chris&LastName=Minnick");

Related Training

Categories

Courses

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss