longforshort
longforshort

Reputation: 84

Uncaught TypeError on jQuery Cross-Origin Ajax Request

I'm currently trying to make a cross-domain Ajax request to an API. I'm using jQuery to make the call and am trying to parse out certain items from the return.

Here's the request:

$.ajax({
    type: 'POST',
    url: 'http://magicseaweed.com/api/APIKEY/forecast/?spot_id=665',
    contentType: "text/plain",
    dataType: "json",
    xhrFields: {
            withCredentials: false
    },
    success: function(data) {
            timestamp = data[0].localTimestamp;
            alert(timestamp);
    },
    error: function() {
            alert("aw crap");
    }
});

Here's the response:

[{
    timestamp: 1366902000,
    localTimestamp: 1366902000,
    issueTimestamp: 1366848000,
    fadedRating: 0,
    solidRating: 0,
    swell: {
        minBreakingHeight: 1,
        absMinBreakingHeight: 1.06,
        maxBreakingHeight: 2,
        absMaxBreakingHeight: 1.66,
        unit: "ft",
        components: {
             combined: {
             height: 1.1,
             period: 14,
             direction: 93.25,
             compassDirection: "W"
        },
        primary: {
            height: 1,
            period: 7,
            direction: 83.37,
            compassDirection: "W"
        },
        secondary: {
            height: 0.4,
            period: 9,
            direction: 92.32,
            compassDirection: "W"
        },
        tertiary: {
            height: 0.3,
            period: 13,
            direction: 94.47,
            compassDirection: "W"
        }
    }
}]

Currently, I'm just trying to get the timestamp string to show in an alert box.

Here's the error I'm getting:

Uncaught TypeError: Cannot read property 'localTimestamp' of undefined
    at Object.success (app.js:11)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

Where's my error?

Upvotes: 1

Views: 1934

Answers (2)

Ekansh Rastogi
Ekansh Rastogi

Reputation: 2516

In your ajax request you have requested response as contentType: "text/plain",

so change this to application/json or parse string as Json with

data = JSON.parse(data);

Upvotes: 2

Plaimanus Lueondee
Plaimanus Lueondee

Reputation: 43

  var parseData = JSON.parse(data); //turn json data to a javascript object
   timestamp = parseData[0].localTimestamp; //then do something to the object

Upvotes: 0

Related Questions