Permission Denied on Ajax xml call, Dynatrace Dashboard - javascript

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.

Related

Request to Google Apps Script URL for deployed WebApp produces 404 error

This issue is very similar to others (like Google Drive Page Not Found - Sorry, unable to open the file at this time for example) posted here. It's not exactly the same, but I do believe it has the same root issue illustrated in that post in that trying to submit a form to a Google App Script while logged into more than to 1 Google account causes /u/1 and/or /u/0 to be added to the script's URL thus producing a 404 Error.
This is using a standard Google account - not G-Suite.
I have a form on a website that submits to a Google Apps Script via AJAX. The script makes some API calls to create a Google Doc containing the data collected by the form.
HTML/Javascript:
<form>
<input type="text" name="full_name">
<input type="text" name="phone">
<input type="submit">
</form>
$('form').submit(function() {
var obj = $(this).serializeObject();
var gurl = "https://script.google.com/macros/s/AKfycbzmhaub3ojPARA-B-Y2uVC2BJZPaRvbgMwMTH9pd7R9aHuAD5M/exec";
$.ajax({
url: gurl,
type: "GET",
data: obj,
dataType: "jsonp",
success: function(data, status, xhr) {
console.log("success");
console.log(data);
});
});
GoogleScripts
function doGet(e) {
var params = e.parameters
var result = {};
try {
result = {
status: start(params),
msg: 'Success',
vals: formData,
rawVals: params,
errs: errors
}
} catch (f) {
result.error = f.toString();
}
return ContentService
.createTextOutput(e.parameters.callback + '(' + JSON.stringify(result) + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Submitting the form while logged into more than 1 Google account in the same browser results in the following error in the console and the form does nothing:
jquery.js?ver=1.12.4-wp:4 GET
https://script.google.com/macros/u/1/s/AKfycbzmhaub3ojPARA-B-Y2uVC2BJZPaRvbgMwMTH9pd7R9aHuAD5M/exec?callback=jQuery112407830193282901534_1608623376571&s&full_name=Dave+Pe&phone=1111111111_=1608623376572
net::ERR_ABORTED 404
When I go to Network tab to view the request, the Header tab there shows the following:
Request URL: https://script.google.com/macros/u/1/s/AKfycbzmhaub3ojPARA-B-Y2uVC2BJZPaRvbgMwMTH9pd7R9aHuAD5M/exec?callback=jQuery112407830193282901534_1608623376571&s&full_name=Dave+Pe&phone=1111111111_=1608623376572
Notice the /u/1/ that have been inserted into the URL that are not present in the URL I pass to my $.ajax() call.
Most of the answers I've found for this issue say to just remove the /u/1/, but since I didn't add it in the 1st place, I don't know where I would remove it from.
Can anyone confirm that this seemingly known issue (of having the URL altered when logged into multiple Google accounts) is what is causing my problems? Any ideas as to how I can go about making my request to:
https://script.google.com/macros/s/AKfycbzmhaub3ojPARA-B-Y2uVC2BJZPaRvbgMwMTH9pd7R9aHuAD5M/exec
and not
https://script.google.com/macros/u/1/s/AKfycbzmhaub3ojPARA-B-Y2uVC2BJZPaRvbgMwMTH9pd7R9aHuAD5M/exec
?? or is there something more deeply wrong with the way I'm trying to use Google Scripts here?
My solution was to move the request from the client side to the server. I submit my form values to a server-side page via AJAX and then on that page, I make an HTTP request with cURL to my Google Apps Script (sending the form data in the body) and send the response back to the client.
Seems to be working... no issues I can think of but that doesn't mean they don't exist. If there are any holes to be shot in that approach, please feel free to unload.
Watered down...
JavaScript
$.ajax({
url: '/ajax-handler.php',
type: "POST",
data: obj
success: function(data, status, xhr) {
console.log("success");
console.log(data);
});
});
PHP
$vals = my_sanitize_func($_POST);
$url = GAS_URL;
$fields = $vals;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
// handle/format response;
$result = ...
print $result;
You can also do whatever you want this way.
Google App Script (Code.gs):
function doGet(e){
var action = e.parameter.action;
if (action=="sendSuccess"){
justSendSuccess(e);
}
}
function justSendSuccess(e){
var output = JSON.stringify({"result":"success"});
return ContentService
.createTextOutput(e.parameter.callback+"("+ output + ");")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
JavaScript Part:
function callGoogleScript(){
console.log("Started");
var url = "https://script.google.com/macros/s/###SCRIPT_ID###/exec";
$.ajax({
crossDomain: true,
url: url,
data: {
"action":"setInfo"
},
method: "GET",
dataType: 'jsonp',
jsonp: "callback",
success: function(data){
console.log("SUCCESS!");
console.log(data);
}
});
}
I tried to run it (authenticated with a single account) and it seems to work. This error seems to happen because you are authenticated with multiple accounts. Also, it seems as it has already been documented at Google Issue Tracker (link to issue). If you want it to make it more visible, you can click the white star (☆) which tells google that you are affected by this issue.
As a side note, notice that the code you make will be executed by everyone as you. This code will have your privileges. Be very careful. Your account limits may also apply.

How to access hp alm with rest api javascript: automatic login

I just want to access ALM via local written javascript in the browser (IE11, Firefox, Chrome) via the REST API but I can not login.
I tried to use the code shown in How to access HP ALM using REST and local javascript? , but there is always the same Error: OPTIONS https://alm.....net/qcbin/authentication-point/authenticate 401 (An Authentication object was not found in the SecurityContext)
Maybe the problem is, that I don't know how to
submit my credentials via XML
as mentioned in the link. Could you please help me?
Me Code is:
function signinTest() {var auth = btoa(name + ":" + password);
$.ajax({
type: "POST",
url: 'https://alm.....net/qcbin/authentication-point/authenticate',
headers: {
"Authorization": "Basic " + auth
},
xhrFields: {
withCredentials: true
},
success: function (data) {
console.log("succes " + data);
},
error: function (data) {
console.log("error ");
console.log(data);
}
});
}
Seems like you have mixed
/authentication-point/alm-authenticate
and
/authentication-point/authenticate
REST resources.
If you want to log in using credentials in XML you need to use alm-authenticate resource (see alm-authenticate doc).
For authenticate you need to send user information in headers and use GET method (see Authenticate doc).
Use data and contentType to send XML via Ajax in the POST.
For example:
function signinTest() {var auth = btoa(name + ":" + password);
$.ajax({
url: 'https://alm.....net/qcbin/authentication-point/alm-authenticate',
data: "<alm-authentication><user>USERNAME</user><password>PASSWORD</password></alm-authentication>",
type: "POST",
contentType: "text/xml",
...

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.

Getting a parseerror from jQuery $.ajax post return using jsonp from Trakt.tv api

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.

Categories

Resources