Ajax response in case of failing - javascript

I'm using ajax to send data to backend.
My issue is that until the result is returning from the server I get the fail message, and after that Success Message.
I presume that it happens, because it goes to else until a response is received. How can I avoid this issue.
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
setResponse(JSON.parse(xhr.responseText).message);
}
else if(xhr.status !== 200) {
setResponseMessage('Form Failed.Please contact support.')
}
};

Your logic is wrong in the onreadystatechange callback, it should be
else if(xhr.readyState === 4 && xhr.status !== 200)

Related

Get the inline message of xhr responseText [duplicate]

This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 7 months ago.
I am receiving json form when submitting a contact form , and I would like to get the inline message of it ;
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
setFormMessage(xhr.responseText.) // Returns a 200 response if the submission is successful.
} else if (xhr.readyState == 4 && xhr.status == 400){
setFormMessage(xhr.responseTex)); // Returns a 400 error the submission is rejected.
} else if (xhr.readyState == 4 && xhr.status == 403){
setFormMessage(xhr.responseText); // Returns a 403 error if the portal isn't allowed to post submissions.
} else if (xhr.readyState == 4 && xhr.status == 404){
setFormMessage(xhr.responseText); //Returns a 404 error if the formGuid isn't found
}
}
this the message when it's 200 :
{"inlineMessage":"Thanks for submitting the form."}
I have already tried to get the value of the inlineMessage like this :
xhr.responseText.inlineMessage
but it didn't work !
any idea how to get that message
this xhr.responseText.inlineMessage is not working because you're treating the response data as an object , while it is JSON string
So you can parse that JSON string with a JavaScript program and access the data as an object.
you might do something like this :
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
const jsonResponse = JSON.parse(xhr.responseText)
setFormMessage(jsonResponse.inlineMessage) // Returns a 200 response if the submission is successful.
}

What is the equivalent of this ternary operator expression?

I have to use a piece of code that comes from another company project.
Unfortunately, it contains an expression that triggers an error in SonarCloud.
The error is:
Non-empty statements should change control flow or have at least one side-effect
The colleague that wrote this line is not in the company anymore.
The line that needs to be modified is xhr.status === 200 ? observable.next(xhr.response), observable.complete()) : observable.error(xhr.statusText);.
Here is the full code:
sendMedia(file: File, presignedUrl: string): Observable<Object> {
return new Observable(observable => {
const xhr = new XMLHttpRequest();
xhr.open('PUT', presignedUrl, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
xhr.status === 200 ?
(observable.next(xhr.response), observable.complete()) :
observable.error(xhr.statusText);
}
};
xhr.send(file);
});
}
If this block equivalent to that statement?
if (xhr.status === 200) {
return observable.next(xhr.response), observable.complete();
} else {
return observable.error(xhr.statusText);
}
Thanks a lot for anyone trying to help!
You are almost there except return statement
if (xhr.status === 200) {
observable.next(xhr.response);
observable.complete();
} else {
observable.error(xhr.statusText);
}

Why Promise return an empty string?

I have a function foo which makes an Ajax request.
I tried returning the data from the callback and got the data with "xhr.onload" successfully but got an empty string("") with "xhr.onreadystatechange".
Could anyone tell me why??
Thank you very much!
function foo(url){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
// xhr.onload = function(){
// if(xhr.status == 200){
// resolve(xhr.responseText);
// }else{
// reject("false")
// }
// }
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState && xhr.status == 200){
resolve(xhr.responseText);
}else{
reject("false")
}
}
})
}
foo(url).then(function (data){
console.log(data)
},function (err){
console.log(err)
})
Your onreadystatechange handler is incorrect. You need to check readyState for the value 4 (not just any truthy value), and you don't want to reject until readyState is 4:
if(xhr.readyState === 4){
if (xhr.status == 200) { // or xhr.status >= 200 && xhr.status < 300
resolve(xhr.responseText);
} else {
reject("false")
}
}
But with modern browsers, you'd probably use fetch instead, which already provides a promise. Just be sure not to make these common mistakes (that's a post on my anemic little blog).
As for why you were seeing what you were seeing, since you called open and send before attaching the handler apparently you didn't get the callback for readyState 1 (opened), so it looks like the first callback you got was when the headers were received (readyState 2), at which point xhr.status would be set — so you were resolving your promise, but of course, the request body hadn't been received yet.

XHR calls return empty

I am new to AJAX and I am trying to make a call to my json file but it is not returning anything in console. I looked into network tab, the xhr status is 200.
const xhr = new XMLHttpRequest();
xhr.readyState = function(){
if(xhr.readyState === 4){
console.log(xhr.responseText)
}
}
xhr.open('GET','data/task.json');
xhr.send();
and task.json is
{
"jobs": [
{
"id": 7,
"title": "Clerk",
"employer": {
"name": "AOL"
},
"location": "Floria",
"salary": "$45k+"
}
]
}
I tried parsing it and using console to print it out but the console is empty as well.
There a few things to notice in the request that you are making.
You need to add the status to 200 because it's the OK status. Meaning that your request go through. So that part will exactly become (this.readyState == 4 && this.status == 200).
You also need to change from using triple equal signs === to == because you are not comparing by TYPE as a triple equals is used in JS.
Using the event handler xhttp.onreadystatechange instead of xmr.readySate. Here is a link to the Mozilla documentation.
So it should become:
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange= function(){
if(xhttp.readyState === 4 && xhttp.status == 200){
console.log(xhr.responseText)
}
}
xhr.open('GET','data/task.json');
xhr.send();
Here is a detailed documentation from W3Schools Documentation with example.
You need onreadystatechange not readyState
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.responseText)
}
}
xhr.open('GET','data/task.json');
xhr.send();
Instead of xhr.readyState you should use xhr.onreadystatechange
like that:
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.responseText)
}
}

DOM exception 11

I'm running this code via the console on http://TheScoutApp.com on line 3 I'm getting a DOM exception 11!!!
var xhr2 = new XMLHttpRequest();
xhr2.onreadystatechange = function() {
console.error(xhr2.statusText); //DOM exception 11!!!
if (xhr2.readyState === 4 && xhr2.status === 200) {
console.error('xhr2');
}
}
xhr2.open("GET","http://thescoutapp.com/extension/update.xml",true);
xhr2.send();
The property xhr.statusText may only be accessed after the request is finished. But the onreadystatechange-callback gets called erlier - the earlier calls have xhr.readyState==1 (=server connection established).
You have to put the assess of xhr.statusText inside a condition:
if(xhr.readyState == 4) {
console.error(xhr.statusText);
}

Categories

Resources