1

I am using this ajax call in my code, but it triggers the error function everytime. Anyone have any idea why this is happening?

$.ajax({
    type:'GET',
    url: 'https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml',
    datatype: 'xml',
    success: function(xml){
        console.log(xml);
    },
    error: function(err){
        alert("ERROR!");
    }
});

To my understanding, the syntax looks correct. Can someone help me to see why this triggers an error, rather than placing the xml into my console? Thanks.

I also see this in the console: XMLHttpRequest cannot load https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml. Origin null is not allowed by Access-Control-Allow-Origin.

chaitanya.varanasi
  • 960
  • 1
  • 9
  • 26

1 Answers1

1

You need to use jsonp to do a cross domain request with ajax - which means you can't request XML using jQuery's ajax method. Here are other related questions.

cross domain issue with Jquery

How to Parse XML Cross-domain in jQuery?

You can use Yahoo API library (YQL) to to get the xml though

Source from http://www.cypressnorth.com/blog/programming/cross-domain-ajax-request-with-xml-response-for-iefirefoxchrome-safari-jquery/

// Accepts a url and a callback function to run.
function requestCrossDomain(site, callback) {

    // If no url was passed, exit.
    if (!site) {
        alert('No site was passed.');
        return false;
    } 
    // Take the provided url, and add it to a YQL query. Make sure you encode it!
    var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

    // Request that YSQL string, and run a callback function.
    // Pass a defined function to prevent cache-busting.
    $.getJSON(yql, cbFunc);

    function cbFunc(data) {
        // If we have something to work with...
        if (data.results[0]) {
            if (typeof callback === 'function') {
                callback(data);
            }
        }
        // Else, Maybe we requested a site that doesn't exist, and nothing returned.
        else throw new Error('Nothing returned from getJSON.');
    }
}
function xmlSuccess(data){
    console.log(data.results[0]);
}
requestCrossDomain('https://s3.amazonaws.com/GSTArticles/GoogleMaps/Landmarks.xml',xmlSuccess);

FIDDLE

Community
  • 1
  • 1
wirey00
  • 33,517
  • 7
  • 54
  • 65