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));
}
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()){
I am using vanilla javascript to making AJAX call to my APIs.
Below is my code which i am calling on click of a simple button:
getUserByUserId : function (callback){
var userid = localStorage.getItem('userid');
var userApiUrl = "http://174.129.30.174:8080/users/"+userid;
var xmlhttp = micropaywall.getAjaxInstance();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
callback(xmlhttp.responseText);
console.log(response);
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", userApiUrl, true);
xmlhttp.send(null);
}
But i get "callback is not a function" at line
callback(xmlhttp.responseText);
Below is my callback function :
getUserByUserIdCallback : function(response){
if(response != "")
{
var res = JSON.parse(response);
var arrAppid = res.appIds;
var userid = res._id;
localStorage.setItem('appid', arrAppid[0]);
var appid = localStorage.getItem('appid');
micropaywall.getUserAccountDetails(userid, appid);
}
}
Please correct me where I am making mistake.
If you don't need to change the "callback" function then you can just call it directly:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
getUserByUserIdCallback(xmlhttp.responseText);
console.log(response);
console.log(xmlhttp.responseText);
}
You would only need to pass in a callback function if you want different behavior when calling the getUserByUserId function.
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
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.