JS XHR JSON payload upload progress - javascript

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.

Related

Access ArangoDB data from browser

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

XMLHTTP Request post data hangs

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

get data from XMLHttprequest

I want to get data in json format.
I have typed this code but it doesn't return anything.
where is the problem in my code?!!
<script language="JavaScript">
var xmlhttp = new XMLHttpRequest();
var url = "http://codeforces.com/api/contest.list?gym=true";
xmlhttp.onreadystatechange = myfunction;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
function myfunction() {
if (XMLHttp.readyState == 0) {
window.alert("Uninitialized");
}
if (XMLHttp.readyState == 1) {
window.alert("loading");
}
if (XMLHttp.readyState == 2) {
window.alert("loaded");
}
if (XMLHttp.readyState == 3) {
window.alert("waiting");
}
if (XMLHttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}
</script>
in the html code, i have a div with id = "id01"
remember that javascript is case sensitive.
edit it to:
var xmlhttp = new XMLHttpRequest();
var url = "http://codeforces.com/api/contest.list?gym=true";
xmlhttp.onreadystatechange = myfunction;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
function myfunction() {
if (xmlhttp.readyState == 0) {
window.alert("Uninitialized");
}
if (xmlhttp.readyState == 1) {
window.alert("loading");
}
if (xmlhttp.readyState == 2) {
window.alert("loaded");
}
if (xmlhttp.readyState == 3) {
window.alert("waiting");
}
if (xmlhttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}
try this:
xmlhttp.onload = function() {
if (xmlhttp.status >= 200 && xmlhttp.status < 400) {
// Success!
var data = JSON.parse(xmlhttp.responseText);
} else {
// We reached our target server, but it returned an error
}
};
disclaimer: i took this code from http://youmightnotneedjquery.com/#json
Just use fetch. It is the modern XMLHttpRequest.
const url = "http://codeforces.com/api/contest.list?gym=true";
fetch(url)
.then(
response => response.json() // .text(), etc.
// same as function(response) {return response.json();}
).then(
jsonString => {
const json = JSON.parse(jsonString);
document.getElementById("id01").innerHTML = json[1].id;
}
);
More Info:
Mozilla Documentation
Can I Use (75% Aug 2017)
Matt Walsh Tutorial

Handling AJAX error (Native JS)

I am trying to handle AJAX error using below code but it is not working
function ajaxPost(url, data, success, error) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
if (typeof success === "function") {
success(xmlhttp.responseText);
}
}else if([404, 500 , 503, 504 ].indexOf(xmlhttp.status) > -1){
if(typeof error === "function"){
error();
}
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xmlhttp.send(JSON.stringify(data));
}
Am I missing any other status code in [404, 500 , 503, 504 ]? I am not reinventing the wheel, I have programmed the whole DOM using native JavaScript and don't want to include 80KB file just for AJAX. Please help me on this.
The above function is successfully posting the data to the server but failed to raise error when server is unavailable. Please help me to handle this.
// try this code
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
var resp=eval('('+xmlhttp.responseText+')');
if( xmlhttp.status == 200 ) {
// success
} else if( xmlhttp.status >= 500 ) {
// internal server error
} else if ( xmlhttp.status >= 402 && xmlhttp.status <= 420 ) {
// error
} else if( xmlhttp.status == 400 || xmlhttp.status == 401 ) {
// bad request & unauthorized error
}
}
};
You can always check for anything that isn't success, for example :
function ajaxPost(url, data, success, error) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
if (typeof success === "function") {
success(xmlhttp.responseText);
}
}else if(typeof error === "function" && (xmlhttp.status > 299 || xmlhttp.status < 200)){
error();
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xmlhttp.send(JSON.stringify(data));
}

Ajax call into httpstatusready=4 doesn't execute

I am using ajax - which works fine - to pass on the value. But when I add the HTTP code, there is no action. Using simple HTTP to show different div values based on http.readystatus. Is this the right format? If not, what is?
if (colorToCheck == gup("Player1")) {
document.getElementById('win').innerHTML = player1 + " wins";
redScore += 1;
//Browser Support Code
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp.readyState == 3 && xmlhttp.status == 200) {
document.getElementById("save").innerHTML = "saving";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//ajax call
var dataString = 'winner=' + player1 + '&player1=' + player1 + '&player2=' + player2 + '&matchNum=' + matchNum;
$.ajax({
type: "POST",
url: "red.php",
data:dataString,
cache: false,
success: function(response) {
$('.result13').html(response);
}
});
}
}
Any help would be highly appreciated! Thanks in advance.
The structure of a Vanilla JS AJAX call is:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","path/to/file.php"); // or "POST" if needed
xmlhttp.onreadystatechange = function() {
if( this.readyState == 3) document.getElementById('save').innerHTML = "saving";
if( this.readyState == 4) {
if( this.status != 200) alert("ERROR: Server returned "+this.status+" "+this.statusText);
else {
// do something
alert(this.responseText);
}
}
};
xmlhttp.send(data); // data is whatever POST data you want. Leave out if using GET.

Categories