I tried to get response from my json url in javascript by using below code:
$(document).ready(function(){
//attach a jQuery live event to the button
$('#getdata-button').live('click', function(){
alert("get data");
$.getJSON('http://vamdemo2.e-isg.com/vamsyncservices/api/site/GetAllSites?username=Admin&password=password', function(data) {
alert(" data alert"+data); //uncomment this for debug
});
});
});
I didn't got any response from above url. If I changed the url from http://vamdemo2.e-isg.com/vamsyncservices/api/site/GetAllSites?username=Admin&password=password to https://www.googleapis.com/freebase/v1/text/en/bob_dylan, getting response. If I open the both url's in browser, both are having data.. But, when I tried to get response from the url using javascript , one url only given response. Where is the problem?? Why another url not giving any response??
Please give me any solution for this...
Thanks in advance...
I've put your code in my browsers and, for me, both URLs are not working.
Even for the googleapis.com URL, when I load your code in chrome and press F12 I get this error:
XMLHttpRequest cannot load https://www.googleapis.com/freebase/v1/text/en/bob_dylan. Origin null is not allowed by Access-Control-Allow-Origin.
This is because JavaScript typically is not allowed to run on domain1 and load URLs from domain2. This is by design, as a security measure.
If
-you are happy to change your client code above AND
-you can make your vamdemo2.e-isg.com server to alter the response when a "callback" query string parameter is added
Then
-there is a solution to this: JSONP
Read more details about how to implement this here:
http://en.wikipedia.org/wiki/JSONP
Related
I'm trying to use a certain service to check for proxies. They have a simple API from which they return JSON. I'd like to get this JSON on my server.
No matter what I do, I either get a CORS request problem or a SyntaxError: missing ; before statement message.
Here's my code:
<h1>Test Page</h1>
Test Button
<script>
function checkProxy() {
console.log("Checking...");
$.ajax({
url: 'http://api.ip2proxy.com/?ip=105.159.246.30&key=demo',
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
}
Clicking my 'button' calls the funtion, which returns the aforementioned syntax error. Changing the datatype to JSON gives me a CORS error.
The strange thing is, when I use a different URL -- example that I found in another StackOverflow thread: http://www.locationbox.com.tr/locationbox/services?Key=3430000202000191008400080609030X20201090060050260003069&Cmd=IlList -- it logs the data just fine.
I'd like to get this JSON on my server.
You'll need to write code that runs on the server to do that. The reason your code is failing is that you're running it on a browser, where the Same Origin Policy comes into play: Your page's origin isn't granted access by that API endpoint via CORS. Unless they allow you access, or they provide a JSONP endpoint you can use instead, you cannot directly query it from a browser.
There is a javascript line (you can try it in the browser console)
window.location.href='http://example.com'
that will push you to http://example.com
In the Browser(Google Chrome)-> Developer Tools-> Network section you may see the Status is 200 for it.
The question is:
how to get the status code 200/404/302 right BEFORE executing
window.location.href='http://example.com'
Thank you.
P.S. jQuery is OK for using.
The only way to get the status code would be to make the request before you navigate there. That means make an Ajax call to the resource and check the status. Only downside to this is the Same Origin Policy so the sites need to be in the same domain or they have to have CORS enabled for your resource.
The HTTP status code are generated by the server, so some HTTP request against the server needs to be executed BEFORE you can get a status code -- so you would need to do an Ajax call on the url -- adapting the simple example in JQuery.get you will have something like;
$.get( "http://example.com", function( data ) {
// Yeahh the URL works, we can do the page switch
window.location.href='http://example.com';
});
There are other examples in JQuery.get which deals with error handling etc, but you can read those for yourself.
Of cause, you don't need the entire page to get just the status, you can execute just a HTTP-HEAD which you can see discussed here
With all of this you may run into cross-site scripting restrictions which you can go an research separately -- there are lot of stack-overflow questions on that already.
I'm just writing a little Instagram app. In a fact when I try to get response from this url in JS :
https://api.instagram.com/v1/tags/search?q=money&client_id=f40dfb17ddd144598d562a6f58179006
but for some reason I dont get an answer and no error at all. If I call the url in my Browser I got a JSON formated answer.
Here my fiddle
http://jsfiddle.net/XQ28k/
Since you are planning to do a cross domain request, you should try the JSONP variant of the API by adding &callback=? to the end of the URL
https://api.instagram.com/v1/tags/search?q=money&client_id=f40dfb17ddd144598d562a6f58179006&callback=?
You cannot access a different domain from your current domain (where you make the ajax call).
It will give you cross origin error
Ajax calls only works on the same domain!
A workaround for this is to call a page in your server that this page will make the remote call to Instagram servers and make an ajax call to this page:
php example - in your server page.php:
$url = 'https://api.instagram.com/v1/tags/search?q=money&client_id=f40dfb17ddd144598d562a6f58179006';
$content = file_get_contents($url);
echo($content); //no need to json_encode cause the response returning a json already!
and in your client side code just call to page.php (which is in your server - so it's the same domain):
$.getJSON("page.php",function(json){
alert(json.data);
});
After browsing through this site, I found that you can get Yahoo weather in a JSON format using forecastjson.
When I run:
$.getJSON("http://weather.yahooapis.com/forecastjson?w=2112762724", function(data){
...
});
I get the following error:
XMLHttpRequest cannot load http://weather.yahooapis.com/forecastjson?w=2112762724. Origin null is not allowed by Access-Control-Allow-Origin.
I've gotten this error before but its normally because I'm trying to load XML cross domain but this is clearly JSON. If you go to the link in the getJSON function, it shows JSON data. Does anyone know why I am getting this error?
Thanks
Using JSON doesn't mean that you will not encounter cross domain problem. That is an object standard.
If you want to make a cross domain request, you should use JSONP.
The url that you are trying to request, doesn't support JSONP request. But you can use YQL instead of that.
here is an example,
var query = escape('select item from weather.forecast where woeid="2295424"');
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=c";
$.getJSON(url, function(data) {
console.log(data);
});
And here is the URL that you can check json result.
DEMO
I have written an XMLHttpRequest which runs fine but returns an empty responseText.
The javascript is as follows:
var anUrl = "http://api.xxx.com/rates/csv/rates.txt";
var myRequest = new XMLHttpRequest();
callAjax(anUrl);
function callAjax(url) {
myRequest.open("GET", url, true);
myRequest.onreadystatechange = responseAjax;
myRequest.setRequestHeader("Cache-Control", "no-cache");
myRequest.send(null);
}
function responseAjax() {
if(myRequest.readyState == 4) {
if(myRequest.status == 200) {
result = myRequest.responseText;
alert(result);
alert("we made it");
} else {
alert( " An error has occurred: " + myRequest.statusText);
}
}
}
The code runs fine. I can walk through and I get the readyState == 4 and a status == 200 but the responseText is always blank.
I am getting a log error (in Safari debug) of Error dispatching: getProperties which I cannot seem to find reference to.
I have run the code in Safari and Firefox both locally and on a remote server.
The URL when put into a browser will return the string and give a status code of 200.
I wrote similar code to the same URL in a Mac Widget which runs fine, but the same code in a browser never returns a result.
Is http://api.xxx.com/ part of your domain? If not, you are being blocked by the same origin policy.
You may want to check out the following Stack Overflow post for a few possible workarounds:
Ways to circumvent the same-origin policy
PROBLEM RESOLVED
In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:
url: "http://mydomain.com/site/cgi-bin/serverApp.php"
But the correct way is to pass the value of url as:
url: "site/cgi-bin/serverApp.php"
Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:
http://mydomain.com/site/index.html
And put
http://www.mydomain.com/site/index.html
In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file
base href="http://mydomain.com/" <--- bad idea, remove it!
If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!
I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:
header('Content-type: application/json');
to ensure that browser get the data as "json data" ...
The browser is preventing you from cross-site scripting.
If the url is outside of your domain, then you need to do this on the server side or move it into your domain.
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
Had a similar problem to yours. What we had to do is use the document.domain solution found here:
Ways to circumvent the same-origin policy
We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:
https://developer.mozilla.org/En/HTTP_access_control