How to get 'getJSON' response header

12,347

Solution 1

I observed many visits to this question and thought it is good to provide the solution to this problem. Unfortunately none of the offered solutions worked and I did two things to solve the problem.

  1. I verified that I have the following codes right after the <?php tag in my server side:

    header("Content-Type: application/*");
    header("Access-Control-Allow-Origin :*");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
    header("Access-Control-Max-Age: 1000");
    header("Access-Control-Allow-Headers: Content-Type");
    
  2. I slightly changed the way I do the call as follows and it always works for me.

    function name(){
        $.ajax({
            type: 'POST',
            crossDomain: true,
            data: {
                data1: data
            },
            dataType: 'text',
            error: function (res, textStatus, errorThrown) {
                alert('Connection Terminated. Please try again');
            },
            success: function(res, textStatus, jqXHR) {
            //Process the result in res;
            },
        });//ajax
    }//function name
    

Solution 2

Do not use JSONP, it isn't really a cross domain request (JSONP explained), it's a hack that only works for GET requests, whereas AJAX allows any http method.

Try preparing your server to allow cross domain requests (more details) and doing this:

$.ajax({
type: "get",
url: "http://192.168.1.102/server/server.php",
crossDomain: true,
cache: false,
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: array,
success: function(data, textStatus, xhr) {
    console.log(data);
    console.log(xhr.getResponseHeader("Content-Length"));
},
error: function (xhr, textStatus, errorThrown) {
    console.log(errorThrown);
}});

Thereby, the xhr object is set and you can access it's header.

Solution 3

Try this:

xhr=$.getJSON('http://192.168.1.102/server/server.php?callback=?',   
  {data:array}, function(res,status,xhr){
    alert(xhr.getAllResponseHeaders()); 
    // not getAllResponseHeader its only getResponseHeader
});

For cross domain use

$.ajax({
  url: 'http://192.168.1.102/server/server.php?callback=?',
  dataType: 'json',
  jsonpCallback: 'MyJSONPCallback', // specify the callback name if you're hard-coding it
  success: function(data){
    // we make a successful JSONP call!
  }
});

Refer this jQuery getJSON works locally, but not cross domain

Docs For getAllResponseHeaders, getResponseHeader and ajax http://api.jquery.com/jQuery.ajax/

Share:
12,347
Espanta
Author by

Espanta

I am a Data Scientist in a leading telecommunication firm in Canada, performing data-X and predictive modeling. I completed PhD in computer science and IT at Department of Computer Systems and Technology at the University of Malaya, Malaysia in 2014 where I was research assistant and part-time lecturer for 3 years. I received M.Sc. (Information Systems) in 2008 and BE (Software Engineering) in 2001. I am currently excitedly working on trigger-base predictive modeling where I predict customer behavior based on their behavioral attributes; i.e., visiting certain store, providing certain feedback, visiting website pages and so on. Reach me if anything interesting!

Updated on June 18, 2022

Comments

  • Espanta
    Espanta almost 2 years

    I need to access the size of response message I am getting from another machine (cross-domain request) using $.getJSON, although I can see the request and response in chrome console, it does not work. Here is my request code:

    xhr=$.getJSON('http://192.168.1.102/server/server.php?callback=?',   
    {data:array}, function(res){
    alert(xhr.getAllResponseHeader());
    }, 
    type='json'); 
    

    when running I get "Uncaught TypeError: Object # has no method 'getAllResponseHeader' " error. When I use

    alert(xhr.getResponseHeader("Content-Length"));
    

    I get "null".

    Please consider that I am using cross-domain get.

  • Espanta
    Espanta about 11 years
    thanks Rohan, I have an Indexed array of number to send th the server. Is is okay if I send data:array. When I do so, the request header becomes full of undefined=&...server/server.php?callback=callback&undefined=‌​&undefined=&undefine‌​d=&undefined. I guess my data should be in a form of key/value, so I did data:{1:123} and sent, but I never receive any reply.
  • Espanta
    Espanta about 11 years
    thanks vhtc, I will try it soon. Can I do POST using this approach as well? I use Apache Tomcat, is it okay then?
  • vhtc
    vhtc about 11 years
    You can make http requests of any type.
  • vhtc
    vhtc about 11 years
    On the server side, you need to add the Access-Control-Allow-Origin header to the response.
  • Espanta
    Espanta about 11 years
    thank you very much Hopefully I will be able to do it tomottow. I will get back to you with results. I have already addedd Accecc-control-allow-origin to the php side. many thanks
  • Espanta
    Espanta about 11 years
    Hi vhtc, I tried & have difficulties. Here is the server code. header("Content-Type: application/json"); header("Access-Control-Allow-Origin :*"); header("Access-Control-Request-Method :GET, POST"); and in client I copied your code. But, in the console error is thrown. This is the error: OPTIONS 192.168.1.102/server/server.ph…ed=&undefined=&undefined=&und‌​efined=&undefined=&u‌​ndefined=&_=13633294‌​85854 send p.extend.ajax callJSON (anonymous function) p.event.dispatch g.handle.h errorThrown I kept ajax in callJSON() function to repeat it 30 times. So, where is wrong? Plz help tnx.
  • vhtc
    vhtc about 11 years
    Once contentType: "application/json; charset=UTF-8", the 'array' you are passing as parameter needs to be a json object. data: {foo : 'bar'}
  • Espanta
    Espanta about 11 years
    Nop I afraid. Since I am generating my array using javascript, I think making a json object becomes slightly tricky. I am now concern about that. Should I choose PhP instead?
  • Aaron Digulla
    Aaron Digulla over 9 years
    The first code block is confusing: It uses getAll... but the comment says not to use it.