Get a JSON file from URL, XMLHttpRequest cannot load error - javascript

I need to read a JSON file from URL and display.
I have read a lot of posts but still couldn't fix the problem.
url : http://webapp.armadealo.com/home.json
I face this error : XMLHttpRequest cannot load
The code is below
$.getJSON("http://webapp.armadealo.com/home.json", function(data){
alert(data);
});
I have tried adding to the url
&callback=?
and making it a jsonp, still no luck. I have also used
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
still no luck.
Is there anything that we need to do at the server side?
People who have faced such an error and have found a solution, Help me out please!
Thanks a lot!

You cannot make cross-domain AJAX requests like that due to security reasons. So if you want to load content from another domain, you will have to use a workaround: JSONP (more info, example)
Use the following code for the AJAX request:
$.ajax({
url: 'http://webapp.armadealo.com/home.json',
type: 'GET',
jsonpCallback: 'myCallback',
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
In order for this to work, you will have to wrap the JSON data in parentheses and add the callback name at the beginning:
myCallback({ ... JSON ... })
EDIT: Just noticed you already tried to use JSONP... Well, at least the above code works for me, perhaps you want to give it a try. ;)

Related

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

jQuery AJAX not receiving JSON from http request

I ame using html with some jQuery to try out some JSON requests. I did a bit of research and tried making something small just to test it out. but when i run the script in my browser(Google Chrome) i dont get anything besides my html/css stuff. here is the code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
console.log("Test");
console.log($.get("https://prod.api.pvp.net/api/lol/euw/v1.1/summoner/by-name/kerrie?api_key=[key]"));
</script>
*[key] is my key from the api owners(not to be shared on the internet).
when i check the network tab it says "304, not modified" i dont if this has anything to do wit it.
I'm just starting with websites and JavaScript/jQuery any help would be helpfull.
For better understanding you can call ajax method as below
$.ajax({
url: 'https://prod.api.pvp.net/api/lol/euw/v1.1/summoner/by-name/kerrie?api_key=[key]',
type: 'GET',
dataType: 'JSON',
async: false,
error: function(){},
success: function(resp){
// resp variable will be your JSON responce
}
}
});

jQuery .getJSON vs .post which one is faster?

Using
$.getJSON();
or
$.post();
I'm trying to send some parameters through a page that is just for AJAX request
and get some results in JSON or html snippet.
What I want to know is that which one is faster?
Assume the HTML file would be simply plain boolean text (true or false)
As others said there is no real difference between the two functions, because both of them will be sent by XMLHttpRequest.
If the server is handling both of the requests with the same code then the handling times should be the same.
Therefore the question can be translated to which one is faster the HTTP GET request or the POST request?
Because the POST request needs two additional HTTP headers (Content-Type and Content-Length) comparing to the GET request the latter should be faster (because less data will be transferred).
But that's just the speed, I think it's better to follow the REST guidelines here. Use POST if you're modifying something, use GET if you want to fetch something.
And one another important thing, GET responses could be cached, but I was having problems caching POST ones.
i dont think it will make a difference both make use of ajax, .post loads the data using http post request where as getJSON uses a http get request more over you dont have to explicitly tell getJSON the dataType
If it is a HTTP action that is retrieving data from the server without persisting (updating) anything, GET is the correct semantic to use.
Both post and get use HTTP so performance difference will be negligible, especially considering the variables of WAN communication.
They are both wrappers/shorthand methods for jQuery.ajax, so there wont be a performance difference.
This is old but ...
We all have to remember about: CSRF/XSRF.
If you do it this way:
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: {
token : 'pass-some-security-token-here'
},
cache: false,
success: function(data) {
//do your stuff here
}
});
you can receive it then like this, nullifying most CSRF/XSRF
if (isset($_POST['token'])) { //you can also test token further
//do your stuff her and send back result
} else {
//error: sorry, invalid, or no security token
}
In many cases GET is an invitation for bad guys, as getJSON uses GET HTTP request.
$.getJSON(); is a shortcut to $.ajax(); which also calls $.post(); so you won't see much difference (but it will be easier to use $.getJSON() directly).
See the jquery doc
[EDIT] NimChimpsky was faster than me...
There are no difference, Because both are using XMLHttpRequest.
First, $.getJSON() is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
https://api.jquery.com/jQuery.getJSON/
Second, $.post() is also a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
https://api.jquery.com/jquery.post/

cross domain jsonp request.. what am i doing wrong?

I am really lost here, and I have no idea what I am doing wrong.
I have exposed an api which gives a json output, and I want to fetch this data from another domain. Since jsonp is way to go, I am trying the code below.. Inspection on firebug shows that the response to the request is proper JSON, but the callback functions never seem to execute. Any help?
$(function(){
console.log('aa');
$.ajax({
url: 'http://domain/api.php',
data: {f:'get_total_playtime',userid:'1',starttime:'2011-01-01',endtime:'2011-12-12'},
dataType: 'jsonp',
success: function(data){
console.log('suceess');
alert(data.time);
},
failure: function(data){
console.log('failure');
}
});
});
If this is not the right way to go about it, can anyone explain the right way?
Inspection on firebug shows that the response to the request is proper JSON
Then that is the problem. You have to return JSONP, not JSON.

Calling a webservice using JQuery

I am using this code from http://www.joe-stevens.com/2010/01/04/using-jquery-to-make-ajax-calls-to-an-asmx-web-service-using-asp-net/
function callWebService(address) {
var result;
$("#result").addClass("loading");
$.ajax({
type: "POST",
url: address,
data: "{}",contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
}
function Success(data, status) {
$("#result").removeClass("loading");
$("#result").html(data.d);
alert("Success");
}
function Error(request, status, error) {
$("#result").removeClass("loading");
$("#result").html(request.statusText);
alert("Error");
}
I don't understand what is wrong with this code. It keeps returning "Error"
Also make sure that the service URL that you're trying to access is in the same domain as your site. AJAX calls won't succeed if you cross domains, since browsers subject AJAX calls to the same domain policy. Can you also include the URL you're trying to access?
If you're trying to access a resource at a different domain, you may want to consider a JSONP request instead. See the jQuery AJAX documentation for a discussion of how to use JSONP.
I think if you combine knowing the URL you're trying to access along with Justin and mohlsen's suggestions, I think we can help.
Your code looks fine at first glance.
I recommend you use FireBug to attempt to isolate the problem further, as it will allow you to see the actual HTTP requests, POSTed data, etc...
A few suggestions based on some code I have doing this. But as others have said, make sure to manually look at the data going out and coming back. Your link references asp.net webservice, is that what you are calling since you didn't mention it.
Make sure the "address" url is of the form /location/page.asmx/methodname
You might need to pass the data to the success method in the call
success: function(msg) {
//msg is a json object, .d is the data field returned by asp.net
if (msg.d.length > 0)
ProcessData(msg.d);
else
HandleError('No data was returned.');
},
error: function() {
HandleError('There was a problem calling the webservice.');
}

Categories

Resources