I'm using Flaskr to generate data via a RESTful API. My call looks like:
http get localhost:5000/v1.0/dataset dataset_id==f7e7510b3c1c4337be339446ca000d22
and returns something like:
{"sites": "a"}
Now I'm tring to fetch this data with my web app. I first ran into a cross-domain error, but after some reading, found out that I could by-pass that error by using jsonp. Basically copying a piece of code I found here, I put this together (I'm new to JavaScript):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
(function($) {
var url = 'http://localhost:5000/v1.0/dataset?dataset_id=f7e7510b3c1c4337be339446ca000d22&callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
$('#data').html('the error was thrown');
}
});
})(jQuery);
</script>
</head>
<body>
<div id = 'data'></div>
<p> place holder </p>
</body>
and accordingly changed my python response to look like:
"jsonCallback({\"sites\":\"a\"});"
If this helps, my flaskr return line is the following:
return callback_function + '({"sites":"a"});'
I'm fairly confident my python side of the problem is good, but I'm not well versed enough in JS to determine where the error is coming from. My goal is to simply display my data on the page.
I'm not sure what's not working with your code. Because you haven't written any error message or what happens when your code runs.
Any way the following script does a JSONP request to http://jsonplaceholder.typicode.com/users/1/todos service and returns one todo item. I have used this only to have a service that returns some data.
If you are going to the developer console in your browser to network and click on the request to the rest service you'll see under response that jQuery is adding a callback to the JSON so you don't need to add it in your URL.
See the following screenshot. (The screenshot is from Firefox.)
I have added a working ajax example below. If you prefer jsFiddle, you'll find the same example here.
(function ($) {
//var url = 'http://localhost:5000/v1.0/dataset?dataset_id=f7e7510b3c1c4337be339446ca000d22';
var url = 'http://jsonplaceholder.typicode.com/todos/1'; // dummy url
var jsonCallback = function (data) {
console.log(data);
$('#data').html(JSON.stringify(data, null, 2));
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>
Related
I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
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.
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
}
}
});
What I'm working on is providing 1 line instant definitions of terms and perhaps one line answers to few logical questions. Suppose a user inputs "JavaScript" and JavaScript visits the url https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1, gets the item "Definition" (Look at the API link to understand, Definition is in the first line itself) and displays its value of Definition and alert the user with the required data.
Anyways my code currently is:
<html>
<head>
<title>Hi</title></head>
<body>
<input id="ddgAPI"><button>Search</button>
<div id="output"></div>
</body>
</html>
Please note that I've not put in the required JavaScript/jQuery code as I'm confused with this. Thank you :)
Because this is a cross-domain request you can only do this with a proxy or with JSONP. Fortunately DuckDuckGo supports JSONP, so you just need to ensure that you add a callback parameter to the URL request like:
https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1&callback=jsonp
... or use the appropriate jsonp parameter with jQuery's ajax method, something like:
$('#ddgAPI').on('keyup', function(e) {
if (e.which === '13') {
$.ajax({
type: 'GET',
url: 'https://api.duckduckgo.com/',
data: { q: $(this).val(), format: 'json', pretty: 1 },
jsonpCallback: 'jsonp',
dataType: 'jsonp'
}).then(function (data) {
console.log(data);
});
}
});
Use jQuery.ajax() to talk to the remote service. url should be https://api.duckduckgo.com. type should be GET. data should be:
var data = { q:'JavaScript', format:'json', pretty:1 };
jQuery will then compile everything into an AJAX request, send it to the server. Pass a function as success so you can do something with the result:
$.ajax({
url: "https://api.duckduckgo.com",
type: "GET",
data: { q:'JavaScript', format:'json', pretty:1 },
success: function(data) { $('#output').html(data); }
});
I have a website hosted on server A that sends a request to a website on server B.
The website on server B has recently seen moved to another server. Lets call that server C.
Since the server migration the information that gets requested is not longer being displayed on server A.
The javascript that server A uses to send the request can be seen below:
<script type="text/javascript">
jQuery(document).ready(function() {
var ppUrl = 'http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372412035546&_=1372412036723';
jQuery.getJSON(ppUrl, function(data) {
jQuery('.ipPopularPosts').append(data.content);
});
});
</script>
Interestingly, if you put the request URL into a broswer, it dislays the correct information.
http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372412035546&_=1372412036723
But when the website requests this information, I get the following javascript errors:
Resource interpreted as Script but transferred with MIME type text/html: "http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372416916349&_=1372416917575". jquery.js:3501
Uncaught SyntaxError: Unexpected token < index.php:1
The error above relates to line 1 on index.php which can be seen below:
<script type="text/javascript">window.jQuery || document.write("<script src='http://www.nowgamernetwork.com/js/libs/jquery-1.5.1.min.js'>\x3C/script>")</script>
For some reason, Server A doesn't like the fact that the response it is getting from server C starts with a '<'.
How can I fix this problem?
Any help would be appreciated!
use &callback=?' in the url
dataType: 'jsonp'
(function($) {
var url = 'http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
$(document.body).html(json.content)
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
<script src='http://www.nowgamernetwork.com/js/libs/jquery-1.5.1.min.js'>\x3C/script>
See the problem?
Fixed it.
The PHP script on server C was using 'ob_get_contents' to pull all of the html into a json format. I noticed ob_start was missing so I added that and it now returns that data in the correct format.
For some reason server B didn't require ob_start to make it work.