1

I am trying to get the contents of http://en.wikipedia.org through an ajax call. For this, I am using jQuery. Here is the code:

jQuery.ajax({
  url:"http://en.wikipedia.org",
  crossDomain: true,
  dataType: "jsonp",
  jsonpCallback: "myCallback"
});

function myCallBack(data){
  console.log("ok");  
}

The problem is that I get in Firebug this error:

SyntaxError: syntax error
<!DOCTYPE html>

So I would say that the html content is fetched, although the callback function is not run. At some point it encounters the specified tag, throws this error and stops running the script.

Do you have any idea where the problem might lie?

Is there any other way to get the contents of a html page? I do not want to use iframes, because that means I will not be able to use or modify its contents.

Dragos
  • 2,911
  • 12
  • 39
  • 55

2 Answers2

3

Its because you're Ajax function expects a json response from the provided url and it gives an html response, thats the reason you are getting a syntax error, the same error you will get from the Chrome debugger as well.

Updated:

What you're trying to do is called a Cross-Domain Request.

"For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed."

Reference

Solution:

You can resolve this issue by having a backend script which will the external pages for you. Like a proxy server, which resides the same domain, so you wont have to face the Cross domain issues. And you can load them, by

$.get(url, success: function(data) { // the url that will fetch the external html page for you, located on the same domain
  console.log("ok");
});
Community
  • 1
  • 1
Viren Rajput
  • 5,426
  • 5
  • 30
  • 41
1

Your issue your having here is that you are calling across domains. Allthough you seem to have realised this and are using jsonp for your request, the document you are trying to pull ie wikepedia is not a jsonp document. So as soon as the ajax finds the html tags it will throw an arror, as you have defined that you are expecting a jsonp response.

You cannot just pull other websites data across domain with javascript due to the cross domain issues, if you want to accomplish what you are doing here you will need to use a back end language to get the data.

Usefull link is http://json-p.org/ Hope that helps

Dominic Green
  • 10,142
  • 4
  • 30
  • 34