Mariah
Mariah

Reputation: 727

Cross-domain $.ajax request is not working

Included below is the code that I am trying to use to display the HTML contents of another page. I am unable to get the code to work and am receiving an error each time. What am I missing here?

$.ajax({
    url: 'http://www.msn.com',  
    type: 'GET',
    dataType : "text/html",
    success: function (result) {
        alert('success');
        alert(result);
    },
    error: function() { 
       alert('error');
}
});

Upvotes: 0

Views: 1497

Answers (6)

MilkyWayJoe
MilkyWayJoe

Reputation: 9092

If you're fine using an external API, you can use YQL (but it's not perfect).

Check this fiddle and you'll see it working. Perhaps it's not for you, just throwing it out there.

Upvotes: 1

Steve
Steve

Reputation: 5853

If you indeed intended to do a Cross-Domain AJAX request and you're looking to retrieve a HTML response you may want to check out this article by James Podolosky, where he discusses piping these sort of requests through YQL and provides a plugin to automate this by overriding the jQuery.ajax function, allowing you to use it as you expected here.

Upvotes: 1

Control Freak
Control Freak

Reputation: 13213

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

Script and JSONP requests are not subject to the same origin policy restrictions.

Source: http://api.jquery.com/jQuery.get/

Upvotes: 3

chaos
chaos

Reputation: 124267

In Chrome, open up Web Inspector (e.g. right-click, Inspect Element) and go to the Console tab, then run that code. You will then actually get to see the cross-domain scripting security error you are triggering.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

You cannot do a cross-domain AJAX request (unless the servers are specifically set up for it).

The best you can do is call a PHP script on your server, which in turn gets the HTML from the other server and sends it back to your page.

Upvotes: 3

gcochard
gcochard

Reputation: 11744

You can only make ajax requests to your own domain. Point it to your own pages and your success function will be called.

Upvotes: 2

Related Questions