Two related questions.
(this is my jquery.js file)
$.ajax
({
type: "GET",
url: "url",
dataType: 'image/png',
async: false,
beforeSend: function (xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Bearer xxxx");
},
success: function (data) {
document.getElementById("myImage").src = data; // (will be in next question)
console.log(data);
}
});
When I get JSON data, it will put that data into the chrome console (developer tools) via the console.log. However with the png I don't see any data. This worries me because in the request response for the picture I see the binary data
�Ս-��tKn�v���6�k�˟>��������7�&=���+���?J�k�����y����L���m�(ψ/
but I need to make sure this is in the data variable because of the .src = data line.
This leads into my next question.... If the image binary data is in the "data" variable, shouldnt it be displayed in my html?
<html>
<head>
<script src="//code.jquery.com/jquery-2.0.0.min.js"></script>
<script src="jquery.js"></script>
</head>
<body>
<img id="myImage" src="" />
</body>
</html>
Thanks!
Why do you need that ajax call at all? just set
document.getElementById("myImage").src = url;
even if you do get contents of the image via the ajax call, get around all browser issues, encoding issues etc., you can't just display that image, becuase the "src" attribute of an img take a URL not a data stream.
Beside that, you code seems fine, if I go to JQuery.com and run this in the console (FireFox - latest), I will get the datastream:
$.ajax
({
type: "GET",
url: "http://jquery.com/jquery-wp-content/themes/jquery.com/i/feature-sprites.png",
dataType: 'image/png',
async: false,
success: function (data) {
console.log(data);
}
});
You may want to ensure your authentication is not failing, and since you are probably running the script on a domain that is different from that of the API you should ensure the API allows CORS (Cross Origin Resouce Sharing) which basically means you can call it from a different domain.
Related
I'm trying to use this to get image URL's http://aminariana.github.io/data-uri-to-img-url/ for sharing on facebook.
I just can't work out how to make the post request using jquery:
# Make a POST request with param 'image[data_uri]' set to the above DataURI input.
# This could be from an HTML form with a textarea, or programmatically using an AJAX POST request.
I have setup a JS Fiddle that creates an image in canvas, converts the image to the datauri http://jsfiddle.net/7asutg7c/ it's just the last part of using jsonp in jquery to send the parameter and get the URL back that I am completely lost on.
var url = 'http://data-uri-to-img-url.herokuapp.com/images.json';.
$.ajax({
type: 'POST',
url: url,
async: false,
// data: dataURL,
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json.url);
},
error: function(e) {
console.log(e.message);
}
});
My initial thought was to set data to the dataURI but I get "Failed to load resource: the server responded with a status of 414 (Request-URI Too Large)" ... so I am a little stuck about how I should be sending that dataURI.
Any help would be greatly appreciated.
Create a JavaScript object like this,
var myData = {
image: {
data_uri: your_data_uri_here
}
};
and then pass that as value of the data parameter of the $.ajax call.
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'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>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function fn(){
$.ajax({
type:'GET',
url: "http://www.enquiry.indianrail.gov.in/ntes/NTES",
data: "action=getTrainForDate&trainNo=16649&trainStartDate=11/04/2014&t=1397216860215&18q1xp3lm5=1ptur1oxbz1i5vwea0u61397214250740",
dataType: "json",
success:function(data){
alert(data);
}
});
}
</script>
</head>
<body>
hi
</body>
</html>
The URL you are requesting returns (function(){location.reload();})(), which is not JSON, JSONP or any form of useful data.
Just to update you need to use jsonp instead of json because you're going to get CORS error otherwise. Updated code is
$.ajax({
type:'GET',
url: "http://www.enquiry.indianrail.gov.in/ntes/NTES",
data: {"action" : "getTrainForDate", "trainNo" : "16649", "trainStartDate" : "11/04/2014", "t" : "1397216860215", "18q1xp3lm5" : "1ptur1oxbz1i5vwea0u61397214250740"},
dataType: "jsonp",
success:function(data){
alert(data);
}
});
Note there's nothing wrong in your way of sending data as string, I just prefer object way.
Now when you make a call you'll end up getting this message (and not data)
Resource interpreted as Script but transferred with MIME type text/plain: "http://www.enquiry.indianrail.gov.in/ntes/NTES?callback=jQuery2119973546624…1397216860215&18q1xp3lm5=1ptur1oxbz1i5vwea0u61397214250740&_=1397220999300".
This is where problem is. If you hit the formed URL, it'll give you JavaScript function as a response and no data. This is what you get as a response
(function(){location.reload();})()
I think, server expects unique token (identified by "18q1xp3lm5" : "1ptur1oxbz1i5vwea0u61397214250740" set), for each request. If condition is not met, it sends reload request to the browser.
Since the call is made through AJAX, it's not able reload the page, but due to reused token, there's no result.
I'm trying to build a .js file that sends data to an external API, waits for a response and interprets the results. The external API is XML-based and accepts an HTTPS Post with the XML as body (content-type; text/xml). I can call the API correctly via cURL.
This is what I have so far:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body onload="CallService()">
<script type="text/javascript">
var webServiceURL = 'https://www.url.com';
var xmlString = '<xml><parameter1>value1</parameter1>
<parameter2>value2</parameter2></xml>';
function CallService() {
$.ajax({
url: webServiceURL,
type: "POST",
dataType: "xml",
data: xmlString,
processData: false,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function() {
jQuery.support.cors = true;
});
</script>
</body>
</html>
When I open the HTML I get an alert saying "error" and nothing appears on the other end (the external API's). Is there a way to do this using just JavaScript/Ajax/jQuery or do I need a "supporting" code that receives the JS call?
When you want to make cross domain queries, you have basically 3 types of solution :
1) use JSONP, which won't interest you if you're using XML and not JSON
2) not really do cross-domain, by setting a kind of proxy (or any type of get) on the server serving the main html page
3) changing headers on the server to specify to the browser that you accept cross-domain queries. This is new but yet accepted by all major browsers. That's called CORS. It's easy to change the headers ("Access-control-...") in all server-side languages so that should now be the preferred way (if you have issues (security, rights, bandwidth, ad, etc.) with cross-domain access to the data you serve, you can restrain the allowed origins).