AJAX api PUT request - javascript

Am I even close to success? I'm trying to use this block of code is jsfiddle to use a PUT request to the API, when using www.hurl.it with the same URL & XML, it succeeds, (woohoo!) but when I try it using this code I have no such luck.
Selecting "RUN" is jsfiddle yields nothing, as in nothing happens at all except the page flashing.
var url = 'https://api.example.com/v1.svc/results/modules/[moduleID]?apikey=[apikey]&source=[source]'
var xmldata = '<ModuleResult><CourseId>JJxblllJXcw1</CourseId><UserId>XaWpNO10m-M1</UserId><Score>100</Score> <Completed>false</Completed><UpdatedAt>2030-04-30T15:36:30</UpdatedAt><Note>JIL</Note></ModuleResult>'
$.ajax({
url: url,
type: 'PUT',
contentType: 'application/XML',
data: xmldata,
success: function(data) {
alert('Load was performed.');
}
});
Any input would be greatly appreciated!

The call wall being completed Cross Origin, the simple proxy prefilter shown below solved my issue.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
Note:
A public proxy is not known for being extremely secure, whoever controls the proxy can see all of your data being pushed across it, so ensure the data is not sensitive if using a public proxy.

Related

Permission Denied on Ajax xml call, Dynatrace Dashboard

I've been trying to get an XML response from a Dynatrace server using REST api. I have no trouble getting an XML response when I put the url through Postman, and I am able to receive a 'text' datatype response from ajax, but not an 'xml' response. I plan to parse this data into json for future use.
The code I am using so far is:
function getXML() {
basicAuth = "Basic " + id + ":" + password;
$.ajaxSetup({
async: false
});
$.ajax({
type: 'GET',
url: dynUrl, //this is the function we defined above
dataType: 'xml',
headers: {
'Authorization': basicAuth //this is for basic authentication, you've already provided UID and PWD above.
},
//when we succeed, the function below will be called.
success: function(respt)
{
data = respt;
}
});
}
This is called in the following function.
function XMLRespond()
{
getXML();
//dom = parseXml(data);
//json = xmlToJson(dom);
return data;
}
data is called and displayed by an html hosted on localhost. However, when I run this, I get a blank screen and the console says "Permission Denied". My debugger gives me:
Failed to open http://localhost:8080/api/Test.html
Any help on this issue would be greatly appreciated!
Solved the issue. Turns out IE (and I suspect other Browsers) can't straight up display data. Converting data to a string bypassed this problem.

Using both cached and non-cached JSON from an Ajax request

I have two JSON sources: getCachedJSON.php and getNotCachedJSON.php. As suggested by the names, the client should cache the results from the first but not the second. Both of these files will issue the appropriate headers to tell the client to cache or not cache the data.
How is this best accomplished?
I came up with the following, but don't know if this is how it should be done. And if it is the right way, should the cached JSON be first requested and then the non-cached JSON, or the other way around?
$.ajax({
//cache: true,
url: "getCachedJSON.php",
dataType: "json",
success: function(cachedJSON) {
$.ajax({
//cache: false,
url: "getNotCachedJSON.php",
dataType: "json",
success: function(notCachedJSON) {
var allJSON = $.extend({}, cachedJSON, notCachedJSON);
console.log(allJSON);
}
});
}
});
Browser manages caching for you. Each time when you're making GET request the browser check if it has this resources in its cache. If it has it then request is not made. To tell browser how to control caching you have to use http headers like cache-control and max-age (try to google for details). You have to set these headers when browsers access you server. You can use chrome's dev tools (network) to inspect if there is any requests made. There you will see if resource is obtained from cache or from request.
If you want event better cache control I recommend you to use service workers or browser sql databases.
Hope I understood your question right.
If you want to make a server request and cache it on the client side, you can make use of the browser's local storage.
You could do something along the lines of this:
var allData = cached(nonCached);
function cached(callback){
var cachedData = localStorage.getItem('cached');
// if locally stored data is found, pass it to the callback
if(cachedData){
callback(JSON.parse(cachedData));
} else {
// Else get it from php script, store it, and pass to callback
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(cachedData) {
var key = 'cached';
localStorage.setItem(key, JSON.stringify(cachedData));
callback(cachedData);
}
});
}
}
function nonCached(cachedData){
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(nonCachedData) {
return $.extend({}, cachedData, nonCachedData);
}
});
}

Call post on external Rest API with Ajax

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.
});

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.

How to get Pingdom checks with JQuery .Ajax?

so far as I can tell my issue is that my GET request is not authorised. But my attempts to add authorisation in headers or as values in the URL (api key, username, password) are not being successful.
eg.
$.ajax({
type: 'get',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
Can anyone advise as to correct Javascript syntax for interacting with the Pingdom API? I believe I'm trying to authorize incorrectly Their documentation focuses on PHP which I'm unable to use in this situation.
https://www.pingdom.com/services/api-documentation-rest/#authentication
I don't think it's possible to use the Pingdom API from Javascript in a web browser.
You'll need to use jsonp to get your browser to allow ajax requests across sites, but according to this response it's impossible to set headers in a jsonp request.
Use CORS Anywhere.
I wanted to get a simple jQuery request working that checked the last Pingdom result for our platform. Because of CORS and the need to specify custom headers for authentication, this didn't seem possible.
I didn't want to setup a proxy server for something so simple so I found this answer and was able to use the CORS Anywhere method, which looks something like this:
// Will use the cors-anywhere proxy if jQuery supports it and crossDomain option is passed in.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
// options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
// Use ajax requests as normal.
$.ajax({
type: 'get',
async: false,
crossDomain: true,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
NOTE: Do not use this if you're passing or retrieving confidential information. You should use your own proxy if you're doing that. But if you're just getting public data, like we were, then this should be a nice and clean method to get around the CORS limitation.

Categories

Resources