Showing posts with label jquery-head-request. Show all posts
Showing posts with label jquery-head-request. Show all posts

Friday, June 22, 2018

jQuery AJAX fetch only headers and decide wheather to get the content | Use jQuery to send a HEAD request with AJAX and get the size of a file | Getting response headers data from an AJAX request with javascript

Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata.
For instance, when querying the API for a list of posts, the response body includes just the content but there are also some other valualbe information sent as headers:
The jQuery code for the AJAX request would look something like this:
$.ajax({
    type: 'HEAD',
    url: 'http://example.com/api.php',
    complete: function (xhr) {
        var contentLength = xhr.getResponseHeader('Content-Length');
        // OR YOU CAN SEE ALL INFORMATION USING
        var headers = xhr.getAllResponseHeaders();
    }
});
Which will output as below:
http://localhost/text-finder/download.pdf >> application/pdf
date: Fri, 22 Jun 2018 06:35:52 GMT
last-modified: Sun, 11 Feb 2018 16:39:41 GMT
server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35
etag: "5ae6f-564f2687e28f8"
content-type: application/pdf
connection: Keep-Alive
accept-ranges: bytes
keep-alive: timeout=5, max=100
content-length: 372335



http://localhost/text-finder/test2.html/forum >> text/html; charset=utf-8
date: Fri, 22 Jun 2018 06:35:52 GMT
server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35
vary: accept-language,accept-charset
content-language: en
connection: Keep-Alive
accept-ranges: bytes
content-type: text/html; charset=utf-8
keep-alive: timeout=5, max=97