I have a rest url http://server1:8080/platform/collections/123-456-789 which returns an HTML file as a byte array.
How can I get the byte array response using Javascript or jQuery running in server2. I tried
jQuery.ajax({
url: "http://server1:8080/platform/collections/123-456-789",
type: "GET",
dataType: "html",
crossDomain: true,
username: "abcd",
password: "abcd",
async: true,
success: function(data) {
alert("1");
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error"+xhr.responseText);
alert("error"+thrownError);
}
});
I don't go into the success method. How can I get the byte array response successfully?
Edit:
Even anyother way to get byte array responce using javascript or jquery is also appreciated
For several servers (with different domains) you need to enable CORS to allow cross-domain ajax requests. It should be possible as both servers are under your control.
On how to receive binary data with jQuery (which is currently not possible), see http://blog.vjeux.com/2011/javascript/jquery-binary-ajax.html
CORS is the newer way to go, but jsonp may be a bit easier...
With JSONP, you will need to wrap your file on server1 in some sort of script so you can set the content-type header to javascript and then JSONencode the file and write it to the response. This could be done in a couple of lines in PHP or server side javascript; you'll want the script to end up returning a "javascript file" containing something like this:
document.getElementById('content-holder').innerHTML="<html>this is my file</html>";
On the client (your static html page served from server2), you can then just place your content holder:
<div id='content-holder'></div>
and then a script to pull in content from server1:
<script type="text/javascript">
var getXsS = function(url)
{
var ss = 's' + 'cr' + 'ip' + 't';
var cst = document.getElementsByTagName(ss)[document.getElementsByTagName(ss).length-1];
var ts = 1*new Date();
var e = document.createElement(ss);
e.async=1;
var tsstr = '_ts1_='+ts;
if((''+url).indexOf('?')==-1){tsstr='?'+tsstr;}else{tsstr='&'+tsstr;}
var url2 = url+tsstr;
e.src=url2;
cst.parentNode.insertBefore(e,cst);
};
getXsS('http://server1:8080/platform/collections/123-456-789');
</script>
Note that if server1 is using SSL then server2 must be using SSL also.
Related
I'm making a simple server to send data to a .json file and receive that data from another page but I have problem how to store data in .json file
I used following code but it didn't work
<script src="jquery/jquery-3.4.1.min.js"></script>
<script>
var _lname = "x";
var _fname = "y";
var _mname = "x";
$.ajax({
type: "POST",
url: "data.json",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
}
});
</script>
Simply POSTing data to a JSON file won't work, as sending a POST request requires the server to listen for requests and do something with the payload you sent. You could make a simple NodeJS or PHP script (or any other server-side language for that matter) that could handle saving the payload to a JSON-file.
When you make a POST request, you send data to a web server.
The web server can do something with the data in the POST request.
By default, it does nothing. Imagine the problems that would be caused if anybody could make a POST request to anyone else's web server and write a new file to it. Google's homepage would be defaced every other second.
If you want to store the results of a POST request, then you need to write server-side code to do it (and you almost certainly will want to perform authentication and authorisation when you do so).
Note that the value of data: in your example code will never be valid JSON. Don't try to write JSON by mashing strings together. Use a library function like JSON.stringify.
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.
Working with the Trakt.tv API. It looks like I'm sending valid json as I'm able to authenticate but the return I receive is a parse error.
Resource interpreted as Script but transferred with MIME type text/html:
http://api.trakt.tv/recommendations/shows/myApiKeyCompleteNumbers?callback=jQuery111000155555475132972_1397674204444&{%22username%22:%22userName%22,%22password%22:%22mySha1PassComplete%22}&_=1397674207093
Uncaught SyntaxError: Unexpected identifier
The return says:
Disallowed Key Characters.
I'm using:
jQuery 1.11.0
Thanks in advance for any help or guidance
$(document).ready(function () {
function success(data) {
alert('data: ' + data);
}
var traktUser = 'myUserName';
var traktHash = 'mySha1Password';
var traktApi = 'myApiKey';
var data = {
'username': traktUser,
'password': traktHash
};
var postData = JSON.stringify(data);
var apiUrl = 'http://api.trakt.tv/recommendations/shows/' + traktApi;
$.ajax({
type: 'POST',
url: apiUrl,
data: postData,
contentType: 'application/json',
dataType: 'jsonp',
}).
done(success);
}); //document ready
You can't make a POST request using JSONP, jQuery is ignoring the POST instruction and making a GET request.
Your data is being placed in the query string and is not properly URL Encoded.
The server is responding with an HTML document containing an error message instead of a JavaScript script formatted according to JSONP rules.
It looks like the API you are trying to use does not support JSONP at all. Since you are passing your own user credentials in the request, this makes sense. JSONP is a hack to work around the Same Origin Policy that is implemented by browsers (these days we can use CORS instead) and there is no point in using it unless you want end user browsers to access the API directly. Since end user browsers couldn't access it without being given your username and password, it doesn't seem likely to be intended to be used that way.
Process the data from the API on your server instead.
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.
I have read a lot of topics about CORS & Javascript and about changing the headers in your post but I can't find the right example I am looking for.
So I'm going to first up start with explaining the situation:
I can not change anything to the webserver since this is out of my reach (It's a SAP Cloud Portal)
I can only change the POST code, so I can only control what I send.
The problem I have is described in the following Post:
jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox
--> My FF & Chrome Headers send a METHOD OPTIONS instead of METHOD POST.
I have written example code that works in IE but not in FF & Chrome:
var dataString = "<result><firstname>example</firstname><lastname>ThisIsSparta</lastname></result>";
var urlString = "http://delyo001.you.local:8000/sap/bc/youconsulting/ws/rest/anonymous/z_names_post";
//Add TO SAP.
var aData =
jQuery.ajax({
type: "POST",
contentType: "application/xml",
url: urlString, // for different servers cross-domain restrictions need to be handled
data: dataString,
dataType: "text",
success: function(xml) { // callback called when data is received
//oModel.setData(data); // fill the received data into the JSONModel
alert("success to post");
},
error: function(xml) { // callback called when data is received
//oModel.setData(data); // fill the received data into the JSONModel
alert("fail to post");
}
});
});
Or
var invocation = new XMLHttpRequest();
var url = 'http://delyo001.you.local:8000/sap/bc/youconsulting/ws/rest/anonymous/z_names_post';
var body = '<result><firstname>perthyrtyrtygop</firstname><lastname>sparta</lastname></result>';
invocation.open('POST', url, true);
invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
invocation.setRequestHeader('Content-Type', 'application/xml');
invocation.send(body);
I have found 2 ways to fix this but without any examples:
- do something with a proxy?
- send specific headers
More information about my problem can be found at:
- http://scn.sap.com/message/13697625#13697625
If you can't set the right headers on the server-side and you can't modify the response for jsonP you should indeed use a proxy.
A proxy script is a sort of middleware. You make a request to the script the script gets the data, and returns it to you. For example php proxy. You can make the same thing in asp, jsp, flash or even java applet.
Now you have your SAP service, a proxy (php)file in a your prefered location, and your local javascript in the same domain as the proxy. You don't even need CORS.
If you want to put the proxy in another domain you have to make sure the php file sends the right headers. (Access-Control-Allow-Origin yourdomain or Access-Control-Allow-Origin * for allow all)