Home Ajax success function not working with returned json data and status 200/304
Reply: 1

Ajax success function not working with returned json data and status 200/304

CoderLee Published in 2018-01-13 02:23:21Z

I'm making an AJAX call that returns a JSON object, and is successfully the JSON in browser. However, the success function isn't fired but rather the error block is hit with the message only saying "error" which isn't much to go on. The status is either 200 or 304 and I can see the object on the network in developer tools so it's there but I can't access that object in the success function.

Here is the ajax call:

    type: "get",
    dataType: "json",
    jsonp: "false",
    url: "http://my.api.url:8080/quote",                                                                                          
    success: function(r){
        var q = r;
    error: function(xhr, status, error) {


{"msg":[{"quote":"quote goes here"}]}

The JSON is generated by an express/node application with response.json() if that effect things, I'm relatively new to those. I have tried setting the jsonp to false, using contentType: 'application/json; charset=utf-8', over datatype json, among other ineffective tries. Any help/critiques are appreciated.

CoderLee Reply to 2018-01-13 04:59:18Z

So the problem here is actually CORS,cross origin resource sharing, since jQuery is calling the API from a different port CORS was blocking the resulting JSON data as per the safety standard. A simple middleware addition to the node.js app adjusting the headers for dealing with CORS solves the problem e.g.

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type, Accept");

So the json was essentially in the browser but inaccessible to any scripts because of the headers. These pages helped a lot should someone else encounter this problem.

Enable Cors
Mozilla Dev

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.433385 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO