1

I tried this below code but it return null data..Please help me to how to get data from url using javascript

function makeHttpObject() {
    try { return new XMLHttpRequest(); }
    catch (error) { }
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (error) { }
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (error) { }

    throw new Error("Could not create HTTP request object.");
}

var request = makeHttpObject();
request.open("GET", "Http URL", true);


var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "Http URL", true );
    xmlHttp.send();
   xmlHttp.responseText;


request.send();
request.onreadystatechange = function() {
    if (request.readyState == 4)
        alert(request.responseText);
};
Devi Prasad
  • 789
  • 8
  • 31

2 Answers2

0

Make sure your browser's JavaScript console is open. It can be opened with the F12 key in most browsers. It will tell you if the code you are trying to run is violating your browser's CORS policy. CORS stands for Cross Origin Resource Sharing, and since a strict policy is typically in place by default in most browsers, you cannot make a request to another website that is not under the same domain as the one making a request.

For example, if I were running code on www.example.com and wanted to do an AJAX request to www.example2.com, it would not work because www.example.com is the originating domain and for security reasons you cannot make requests to www.example2.com-- they are different domains.

You can get around this by disabling security on your browser (here's how to do it in Chrome). But be aware that your website visitors WILL have security enabled, so please do not design your code to require this major security hole to be exposed.

Community
  • 1
  • 1
kevin628
  • 3,342
  • 3
  • 23
  • 43
0

You will encounter problems with CORS. Simply put, CORS is a mechanism to prevent exploits on the client-side caused by malicious javascript.

If you can, I'd recommend enabling CORS server side. That means that you have access to the backend of the server you are retrieving the data from.

If you don't have access to the server you want to retrieve the data from, then you need to do it at another level. For example in PHP a basic methos is with cURL

Marius P.
  • 312
  • 5
  • 12
  • I don't know of any way to make it in JavaScript for all visitors without enabling CORS on the server where you would get the data from. Maybe with [Node.js](http://nodejs.org/docs/v0.5.2/api/http.html#http.request), but that is if you are using Node.js on your server. – Marius P. Aug 12 '15 at 12:57