1

I am fetching data from a URL using an AJAX call. It is giving a json object to me.

When I run the application, the page is working fine in IE with a conformation that the page is accessing information that is not under its control.

This poses a security risk. Do you want to continue?

But that is not working in other browsers like Firefox, Chrome, Safari, etc.

i don't know what is the problem. Please explain to me why it is occurring and how to solve the issue?

My Code:

<!DOCTYPE html>
<html>
<head>
    <title>Search Engine</title>
    <script src="JS/jquery-1.4.2.min.js"></script>
    <script>
    $(document).ready(function () {
        $.support.cors = true;
        // create a script tag element
        var script = document.createElement("script");
        // set the attribute, using the URL to pass data via query parameters
        script.setAttribute("src", "http://192.168.13.111:7090/?uname=bhagirathip&wt=json&fl=*,score");
        script.setAttribute("type", "text/javascript");
        // add the script tag to the document head, forcing an HTTP request
        document.getElementsByTagName("head")[0].appendChild(script);
    });
    function Search() {
        function callbackJsonHandler(data) {
             alert(data);  // This is the JSON data
        }
    }
</script>
</head>
<body>
    <form id="form">
        <div style="text-align: center">
        <input type="search" id="searchInput" autofocus />
        <input type="button" id="btnSearch" onclick="Search()" value="Search" />
    </div>
</form>
</body>
</html>
bhagirathi
  • 521
  • 6
  • 23
  • As noted by `jmort253` in the answer below, you can use `jsonp` with `callback` to implement it, which should be easy as you are using `jquery`. – web-nomad Oct 16 '12 at 08:05
  • I'm not clear on what you're trying to do. You're still trying to make a cross domain ajax call, which isn't going to work, and you're also making a script tag request in the document.ready, which will work to make the request, but to retrieve the data, the data must be sent back to the browser as a function call. You need a `function callbackJsonHandler(data)` like what I put in my answer, and your server must send back a `callbackJsonHandler({ /*JSON goes here */);`. It would also help to see the server side code that's involved in sending the response. Consider adding that in an [edit]. – jamesmortensen Oct 18 '12 at 09:09
  • Can you please share the step by step approach. actually i am very weak in jquery. i have to change in the server?? Actually i don't have access to the server – bhagirathi Oct 18 '12 at 10:08
  • I added another answer describing the proxy method. It's a little broad, and you're missing details like what server-side language you're using, who owns the server, and other important details, but it should get you started. Good luck! – jamesmortensen Oct 18 '12 at 21:11
  • I am using asp.net C# as server side. – bhagirathi Oct 19 '12 at 06:45
  • My URl is [Click here](http://192.168.10.113:8080/solr/select/?q=asp.net%20session%20management&indent=on&hl=true&hl.fl=id,name&wt=json&fl=*,score) This is show the data what i am trying to fetch. – bhagirathi Oct 19 '12 at 06:46
  • Server side i added Response.AppendHeader("Access-Control-Allow-Origin", "*"); Response.AppendHeader("Access-Control-Allow-Methods", "POST"); by seeing this link http://stackoverflow.com/questions/6516591/how-to-implement-access-control-allow-origin-header-in-asp-net still i didn't access the data you have written PHP code so i can't proceed with your second answer – bhagirathi Oct 19 '12 at 07:00

2 Answers2

2

You can't make cross-domain AJAX calls across domains. This is a security feature in web browsers to prevent malicious JavaScript code from scraping rendered data in a web page and then shipping it off to some rogue website on some other domain.

By restricting AJAX requests to same domain, browser vendors ensure that JavaScript imported from other sources cannot send data to any server other than the server the HTML page was served from.

In Internet Explorer, it's prompting you, but any smart user who encounters such a message is likely to say no. Presenting your users with such warning messages is not a good design practice and does not inspire confidence in the legitimacy of your application.

The only way that you can send data across domains is to use a browser hack technique called "script tag remoting", which essentially involves using HTML elements that aren't restricted by the same domain policy. For instance script tags can make HTTP GET requests to any server:

// create a script tag element
var script = document.createElement("script");

// set the attribute, using the URL to pass data via query parameters
script.setAttribute("src","http://192.168.9.11/userInput/?key="+userInput);
script.setAttribute("type","text/javascript");

// add the script tag to the document head, forcing an HTTP request
document.getElementsByTagName("head")[0].appendChild(script);

Using this method, you can send data to a remote server. Note that, to get JSON data back, you must wrap it, or pad it, in a JavaScript function and define a callback in the JavaScript code to handle the response:

function callbackJsonHandler(data) {
    alert(data);  // This is the JSON data
}

And your server-side code must return content text/javascript, calling the handler, and passing your JSON as an argument:

callbackJsonHandler({"key":"value","key1":"value2"});

When the browser downloads the JavaScript to the browser, the JavaScript runs immediately, giving you a hook to use to access the JSON in the response.


Since you're using jQuery, you can also check out jQuery JSONP, or JSON with Padding, which can be used to generate a JavaScript response so that you can handle callbacks from these requests to the remote server. Note that the server must be setup to handle JSONP requests for this to work properly, similar to the above setup.

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • Is there any other method to access the cross domain data with out using ajax. I read some where that if we made the Access-Control-Allow-Origin to (site or *) we can access the cross domain data. – bhagirathi Oct 16 '12 at 09:35
  • lol, yes. Script tag remoting and JSONP. Neither of those are AJAX. :) Well, you could use a proxy, but that's a bit more complex. Basically, your page calls your server via AJAX, and your server makes the HTTP request to the remote server, then takes the response and sends it back. `page -> your server -> remote server` – jamesmortensen Oct 16 '12 at 09:37
  • Can you please share the other ways to fetch the data. – bhagirathi Oct 16 '12 at 09:39
  • I gotta run @bhagirathi, sleep calls, but this should help you get started: http://stackoverflow.com/q/10675241/552792 and http://stackoverflow.com/q/7638773/552792 Good luck! :) – jamesmortensen Oct 16 '12 at 09:44
  • hi jmort253 i tried but not succeed. Please help Please point out what I did wrong? – bhagirathi Oct 18 '12 at 08:57
  • "I read some where that if we made the Access-Control-Allow-Origin to (site or *)" - You read that most likely in the [MDC documentation on Cross Domain Origin HTTP Access Control](https://developer.mozilla.org/en-US/docs/HTTP_access_control). If you can't access the server you're making the request to and change the header, then it won't work. – jamesmortensen Oct 18 '12 at 20:51
0

Another solution to the issue of making cross-domain requests from a browser whose HTML document is served from exampleA.com to a server whose domain is exampleB.com is to use a proxy.

Let's assume that the HTML document you're working with is served from exampleA.com. You own exampleA.com, and you can access the server side and client side code. exampleB.com, on the other hand, is a remote server owned or controlled by someone else. exampleB.com has some data you want to use in exampleA.com.

We know that AJAX won't work, because of the same origin policy, which is in place to protect rogue apps from doing bad things with people's data. However, servers aren't restricted to same domain policy. This means that your app can do the following:

||exampleA.com/test.html|| ---> http req --> ||exampleA.com/getData|| --http req --> ||exampleB.com/getJSON||

Server-side: (As in your server, exampleA.com):

In other words, on your server that you're using to serve the HTML, you write some code that makes an HTTP request from your server to the third-party server:

// JSON URL which should be requested
$json_url = 'http://www.exampleB.com/getJSON';

// Initializing curl
$ch = curl_init( $json_url );

// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') 
);

// Setting curl options
curl_setopt_array( $ch, $options );

// Getting results
$result =  curl_exec($ch); // Getting JSON result string

See Getting JSON Data with PHP Curl for more details. Each server-side platform has the ability to make HTTP connections to servers.

// now, send the data in the response
HttpResponse::status(200);
HttpResponse::setContentType('application/json');
HttpResponse::setData($result);
HttpResponse::send();

See PHP HTTPResponse. Again, whatever language you're working with should have the ability to return data from a string.

Put the above code in a file called "getJSON.php", assuming you're using PHP. Make sure there is no whitespace between the opening <?php and the beginning of the document; otherwise, you will not be able to set the headers. There is likely a better way to send this response, but since your platform isn't specified, I'll leave that as an exercise for the reader.

Client-side code:

    var searchURL = "/getJSON.php"; //From this URL json formatted data is present.
    $.ajax({
        url: searchURL,
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            try {
               alert(data);
            }
            catch (err) {
               alert(err);
            }
        }
    });

Now, in the above JavaScript code, you make a same-domain AJAX request to your server exampleA.com, and then your server makes a request on your behalf to exampleB.com to get the data, then exampleA.com returns the data in the response to the browser.

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120