I want to get access to JSON data from arangoDB, which I installed locally from the browser (own interface). I get the "401 Unauthorized" request, how can I fix this?
function getRequest(){
alert("test")
var request = new XMLHttpRequest();
request.open("GET","http://root#localhost:8529/_db/_system/_api/document/FC_ACTUAL_SALES/945545",true);
request.setRequestHeader('Content-Type','application/json');
request.setRequestHeader('Access-Control-Allow-Credential','true');
request.responseType = 'json';
request.addEventListener('load', function(event) {
if (request.status >= 200 && request.status < 300) {
console.log(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send();
}
You are not using basic authentication.
Change your function to this:
function getRequest(){
var request = new XMLHttpRequest();
var user = "root";
var pass = "";
request.open("GET","http://root#localhost:8529/_db/_system/_api/document/FC_ACTUAL_SALES/945545",true);
//Use Basic authentication
request.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
request.setRequestHeader('Content-Type','application/json');
request.setRequestHeader('Access-Control-Allow-Credential','true');
//request.responseType = 'json'; <--Notice it was removed
request.addEventListener('load', function(event) {
if (request.status >= 200 && request.status < 300) {
console.log(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send();
}
Related
Any way to get the progress while uploading a big JSON payload string using XHR?
in my code, it only prints 100% once it is completed, even the json payload size = 30MB
let xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.addEventListener("progress", function (evt) {
console.log(evt.lengthComputable); // false
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log((Math.round(percentComplete * 100) + "%"));
}
}, false);
xmlhttp.onreadystatechange = (event) => {
if (xmlhttp.readyState === 4 && xmlhttp.status >= 200 && xmlhttp.status <= 299) {
let res = JSON.parse(xmlhttp.responseText);
if (typeof this.options.onVideoGetsUploaded === "function") {
console.log('success')
}
} else if (xmlhttp.readyState === 4 && xmlhttp.status >= 400 && xmlhttp.status <= 550) {
//error while uploading
console.log(xmlhttp.statusText)
}
};
xmlhttp.open("POST", this.options.uploadEndPoint, true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({
data: base64data
}));
I just went through some old code where I’ve done this. For uploading I did this
var request = new XMLHttpRequest();
// before opening your request
request.upload.onprogress = function(e) {
// progress in % is: Number(e.loaded / e.total * 100)
};
// open and send request
It seems weird and I remember spending some hours trying to figure this one out. Maybe you could also do:
request.upload.addEventListener(“progress”, callback())
You may set content-length header in you request, then the evt.lengthComputable can be true.
I use AJAX requests to make the user area of my website.
A "Log off" button must be displayed only when the user is connected.
For connecting a user, here my AJAX request:
function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
document.getElementById("popup_login").innerHTML += this.responseText;
if (isUserLogged()){
var x = document.getElementById("log_off");
x.classList.remove("inative_logoff");
x.classList.add("active_logoff");
}
}
};
var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);
xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}
And here my AJAX request to check if a user is connected:
function isUserLogged(){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(this.responseText);
if (this.responseText == "true") return true;
else return false;
}
};
xhr.open("POST", "php/is_user_connected.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}
My "Log off" button doesn't display for some reason.
function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
document.getElementById("popup_login").innerHTML += this.responseText;
isUserLogged();
}
};
var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);
xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}
----------
function isUserLogged(){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(this.responseText);
if (this.responseText == "true"){
alert("ok");
alert("test function");
var x = document.getElementById("log_off");
x.classList.remove("inative_logoff");
x.classList.add("active_logoff");
}
else {
//do your other code..
}
}
};
xhr.open("POST", "php/is_user_connected.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}
You can try if (isUserLogged() == true){ instead if (isUserLogged()){
let httpRequest = new XMLHttpRequest();
let FHIRserverAddress = '192.168.200.139:3012';
let url = 'http://' + FHIRserverAddress + '/model?starttime=' + startTime + '&endtime=' + endTime;
httpRequest.open('GET', url);
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
let currentModel = JSON.parse(httpRequest.responseText);
console.log('returning a valid model');
return callback(null, currentModel);
} else if (httpRequest.status != 200) {
console.log('get model call failed');
}
};
I can see the network call in Chrome dev tools and response status coming back is 200. The above call always get a 0 for the request status.
Anyone see what I am doing incorrectly?
I'm trying to create an AJAX call with the post method, and can't get it to work right. The script hangs at the processing stage (readyState does not go on to 4).
I'd appreciate it if someone could enlighten me on the issue here. I've looked at a couple of tutorials, and it seems that my code -should- work.
function newRequestPost(url, post, threadid, cfunc) {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "post="+post+"&threadid="+threadid;
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params);
}
function openModalPreview(threadid) {
var post = document.getElementById("post_txt").value;
newRequestPost("url", post, threadid, function() {
if(xmlhttp.readyState == 1) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Loading...";
}
if(xmlhttp.readyState == 2) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Received";
}
if(xmlhttp.readyState == 3) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Processing...";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = xmlhttp.responseText;
}
});
}
How can I do this in my function: while Post() is working I want to display a loading sign.
function Post() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('new_story_post').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var textid = document.getElementById("textid").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'post.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("textid=" + textid);
// 3. Specify your action, location and Send to the server - End
}
You are using it in your code already. Please check the documentation about the onreadystatechange event.
The onreadystatechange event is triggered every time the readyState changes. The readyState property holds the status of the XMLHttpRequest.
Hope this helps.
Edit: Example here
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#loading").append('Loaded. Status is ' + xmlhttp.readyState + '<br />');
} else {
$("#loading").append('Working... Status is ' + xmlhttp.readyState + '<br />');
}
}
Algorithm
Display a loading sign before invoking your service.
Hide it when the service has responded.
Implementation
Update your function:
function Post() {
// 0. Display the loading sign
document.getElementById("loading-overlay").style.display = "block";
// 1. Create XHR instance
// ...
// 2. Response handler
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('new_story_post').innerHTML = xhr.responseText;
}
// Hide the loading sign whatever the response is
document.getElementById("loading-overlay").style.display = "none";
}
}
// ...
}
Append the loading sign to the body:
<div id="loading-overlay">Loading...</div>
Add some CSS:
#loading-overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 999;
text-align: center;
display: none;
}
Bonus
You could use a callback to better decouple your code.
function Post(textid, fn) {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} else {
return fn(new Error("Ajax is not supported by this browser"));
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200) {
fn(null, xhr.responseText);
} else {
fn(new Error('Request failed'));
}
}
};
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'post.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("textid=" + textid);
// 3. Specify your action, location and Send to the server - End
}
Usage:
// Display the loader
document.getElementById("loading-overlay").style.display = "block";
// Get the textid
var textid = document.getElementById("textid").value;
// Call the service
Post(textid, function(err, res) {
if (err) {
// Handle error
} else {
// Hide loader
document.getElementById("loading-overlay").style.display = "none";
// Update view
document.getElementById('new_story_post').innerHTML = res;
}
});