I'm trying to create a plugin to check some values hosted on a local site. the auth on the page is done via Windows Authentication.
so I was trying to create an xhr request, but that still gave me 401
// method 1
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true, "User","Password");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
}
same for an ajax request (with the webtoolkit.base64.js)
// method 2
function make_basic_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
function get_info2(url){
var auth = make_basic_auth('User','Password');
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});
}
So is it just impossible to fetch that data in via an extention, or am I doing something wrong?
Related
I am currently trying to figure out how to query the API of a calendar on teamup.com and retrieve data (events in the calendar) from it.
There's a code example on their website: Querying the API via JavaScript / CORS
I tried to make it work in Visual Studio, so I had to install XMLHttpRequest via npm and add a require code line:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
// Creates a CORS request in a cross-browser manner
function createCORSRequest(method, url) {
var apiKey = 'API_KEY'; //placeholder for api key
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari/IE10+.
xhr.open(method, url, true);
xhr.setRequestHeader('Teamup-Token', apiKey);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE8/IE9.
xhr = new XDomainRequest();
// XDomainRequest does not support querying HTTPS from HTTP pages
if (window.location.protocol === 'http:') {
url = url.replace('https://', 'http://');
}
if (-1 === ['GET', 'POST'].indexOf(method)) {
alert('XDomainRequest only supports GET and POST methods');
return;
}
if (-1 === url.indexOf('?')) {
url += '?_teamup_token=' + apiKey;
} else {
url += '&_teamup_token=' + apiKey;
}
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Sends the actual CORS request.
function makeCorsRequest(url, successCallback, errorCallback) {
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function (xhr) {
if (xhr.target.status < 400) {
if (successCallback) successCallback(xhr.target);
} else if (errorCallback) {
errorCallback(xhr.target);
}
};
xhr.onerror = function (xhr) {
if (errorCallback) {
errorCallback(xhr.target);
}
};
xhr.send();
}
// Send a GET request for all events in a date range
makeCorsRequest(
'https://api.teamup.com/ks73ad7816e7a61b3a/events?startDate=2015-06-01&endDate=2015-06-05',
function(xhr) {
var data = JSON.parse(xhr.responseText);
alert('Successfully Received: ' + JSON.stringify(data));
},
function(xhr) {
var data = JSON.parse(xhr.responseText);
alert('Request failed with code '+ xhr.status +': ' + JSON.stringify(data));
}
);
When I try to run the program per node I get this terminal output:
PS C:\Users\...\Documents\GitHub\teamup-test> node team-up-test.js
C:\Users\...\Documents\GitHub\teamup-test\team-up-test.js:45
if (xhr.target.status < 400) {
^
TypeError: Cannot read properties of undefined (reading 'target')
at exports.XMLHttpRequest.xhr.onload (C:\Users\...\Documents\GitHub\teamup-test\team-up-test.js:45:17)
at exports.XMLHttpRequest.dispatchEvent (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:591:25)
at setState (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:614:14)
at IncomingMessage.<anonymous> (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:447:13)
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
So it seems like the program cannot read xhr.target.status, but why?
Summarized: I want to fetch calendar event data from my calendar on team-up per JS and display that data on a discord bot.
I am wondering if I even do need CORS since it's only for browsers. Hoping someone could guide me into the right direction please.
The code tutorial here: https://apidocs.teamup.com/#querying-the-api-via-javascript--cors is to be executed in the browser, in the client. I don't think it can be used in the server. Remember, Node.js is a back-end language, it runs on the server, not on the browser.
You can make an API call in Node.js with the code below, but you should study Axios later
const https = require('https');
const options = {
hostname: 'api.teamup.com',
path: '/ks73ad7816e7a61b3a/events?startDate=2015-06-01&endDate=2015-06-05',
headers: {
"Teamup-Token" : "API_KEY"
},
};
https.get(options, (resp) => {
let data = '';
resp.on('data', (receivedDataBuffer) => {
data += receivedDataBuffer;
});
resp.on('end', () => {
let receivedDataAsJSON = JSON.parse(data);
//do what you need with the json
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
So I have used the below function to detect an ajax call.
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==1){
alert('server connection established');
}
if(realXHR.readyState==2){
alert('request received');
}
if(realXHR.readyState==3){
alert('processing request');
}
if(realXHR.readyState==4){
alert('request finished and response is ready');
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
It is working but now I need the url of that particular ajax request. I have functions like below:-
function loadFundSimulation(num_days = ''){
var url = "<?php echo site_url('investment_plan/simulation/FUND'); ?>";
$.post(url, data).done(function (response,status,xhr) {
#....code....#
}).fail(function (data) {
#....code....#
});
}
When the ajax is being called at that time I want url of this functions. I have many functions like this. When I get the url I want to append ?debug = 1 at the end of the url. I have tried alert(this.url); but it was returning undefined. Any help will appreciated. Thanks in advance.
Edit
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
this.addEventListener("readystatechange", function(event) {
if(this.readyState == 4){
var self = this;
var response = {
method: method,
uri: uri,
responseText: self.responseText
};
response.uri = uri + '?debug=1';
console.log(response);
} else {
console.log(this.readyState);
}
}, false);
open.call(this, method, uri, async, user, pass);
};
I have got the url of that ajax request and I appended ?debug=1 as well. When I console.log(response); I see the url is being changed but I still don't see any error. Please let me know I have to do anything else for that.
After searching a lot this is the best way to do this. Though only tested on chrome.
(function() {
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
arguments[1] = arguments[1] + '&debug=1';
console.log( arguments[1] );
return proxied.apply(this, [].slice.call(arguments));
};
})();
Hi there i am stuck and somehow don't find the solution. It seems simple but, well ok. Here it goes. I have a mobile service in Azure and i want to reach that one with javascript. How do i get around the 401 Unauthorized? I tried with the documentation supplied from MS but no luck. This is what i got so far (adding the key to the url is not working of course) what can i add to get it to work?
var client = new WindowsAzure.MobileServiceClient(
"https://cdshop.azure-mobile.net/",
"vGpqzyApJXXXXXXXXblQCWne73"
);
var getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
$(function () {
$('#clickme').click(function () {
getJSON('http://cdshop.azure-mobile.net/api/cds/total?key=vGpqzyApJXXXXXXXXblQCWne73', function (err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}
});
});
});
If you are creating your own HTTP requests, you need to set a request header called X-ZUMO-APPLICATION with your Application Key, e.g. "vGpqzyApJXXXXXXXXblQCWne73", for tables and APIs that are set to "application" or "users". (Assuming you are still using Mobile Services; the newer App Service does not use this X-ZUMO-APPLICATION header.) Tables and APIs set for "users" also need an X-ZUMO-AUTH request header with the user's authentication token.
Alternatively, you can use the MobileServiceClient you created in the first line, and it will do this for you. This page has examples for calling APIs and tables. For your example:
client.invokeApi("cds", {
body: null,
method: "get"
}).done(function (data) {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}, function(error) {
alert('Something went wrong: ' + error);
});
A simple guide to making a GET request to get a user's messages through Gmail API can be found here.
But the way we are instructed to do the request is in the following manner:
function getMessage(userId, messageId, callback) {
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': messageId
});
request.execute(callback);
}
Is it possible to make the request using the good ol' XMLHttpRequest object on the client side? If so what parameters should be passed into the call?
I have tried this:
var getMessages = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
console.log(xhr.responseText);
}
xhr.open( "GET", "https://www.googleapis.com/gmail/v1/users/me/messages", true );
xhr.send();
}
But I get a 401, even after authenticating.
As it states in this answer, you should pass the access token as a query parameter with the name access_token, or prefix the authorization header value with "Bearer", like so:
xhr.setRequestHeader("authorization", "Bearer " + userToken.access_token);
Is it possible to make an ajax post without having an HTML form? And if it is how should i do it and what PHP variable is used to fetch the variable? The PHP is inside the fetched file. I'm not using any framework.
function ajax(instruction, push, url, callback){
var xmlhttp; // the object for the httprequest
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() { // every time the readystate changes
ajaxLoad(xmlhttp.readyState); // Calls function with the ready state each time it uppdates
if (xmlhttp.readyState == 4) { // status 200 = sucessfull page! NOT 404! // 1 2 3 4 are states of the request (4 is when it's done)
// When load bar is complete
if(xmlhttp.status == 200){
callback(xmlhttp.responseText); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
}
else if(xmlhttp.status == 404){ // Could not find file
ajaxError() // Function that will call the ajax but with the error file
}else{}
ajaxDone(); // activates all the nessesary js to check what to do with some parts of the site
}
else{}
};
xmlhttp.open(instruction,url, true); // sends a the var q to the next php file
if(instruction === "GET"){
xmlhttp.send(''); // Sends the request
}
else if(instruction === "POST"){
xmlhttp.send(url); // Sends the request
}
else{
console.log("This ajax does not support " + instruction + " requests.");
}
if(push == true){ // Change the link to the url of the ajax with
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)
return; // exit's the function
}else{}
var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file
window.history.pushState({path:urlPath},'',newLink); // the push
}
else{}
}
To page 1
You can find some answers here, about how to make Vanilla JS Ajax call:
http://www.sitepoint.com/guide-vanilla-ajax-without-jquery
About to send without forms, you already have the response here:
Send POST data using XMLHttpRequest
You can get your params server-side(php) with the global variables $_GET["your_param_name"] and $_POST["your_param_name"], they are arrays so I think you know how to use them.
Of course, you can make AJAX request in pure js, even jquery handle ajax request in pure js in behind.
JavaScript:
var ajax = {};
ajax.x = function () {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
Call Ajax Method: I will recommend you to not use it in onclick.
ajax.get('ajax.php',{DATA_TO_PASS},function(response) {
//Do something with response
console.log(response);
},true);
$_GET to receive the ajax data;
OR:
ajax.post('ajax.php',{DATA_TO_PASS},function(response) {
//Do something with response
console.log(response);
},true);
$_PSOT to receive the ajax data;
You don't need a form to use ajax post.
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
as the same way you are using form you can fetch the values from php using $_POST