Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.

Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}

Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):

$.ajax({
    type: 'GET',
    url: 'http://username:[email protected]/api/v1/projects.json',
    contentType: 'application/json',
    dataType: 'jsonp',
    converters: {
        'jsonp': jQuery.parseJSON,
    },
    success: function(data) {
        alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(JSON.stringify(jqXHR));
        console.log(textStatus+': '+errorThrown);
    }
});

If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.

It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")

like image 497
therealklanni Avatar asked Mar 17 '11 21:03

therealklanni


1 Answers

So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.

It works just as well, it just requires an extra step is all.

Just for anyone that was looking for a solution.

like image 121
therealklanni Avatar answered Nov 14 '22 02:11

therealklanni