Get the inline message of xhr responseText [duplicate] - javascript

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.
}

Related

Why if and else both condition executing at same time in JavaScript | If and Else Condition

Why If and else condition work both in JavaScript. if (xhr.readyState == 4 && xhr.status == 200)
I am working on php MVC project.
I created a profile edit page in background JavaScript If and Else both code executing. profile edit Successfully but else code work and it's show error "Sorry, this content isn't available right now".
why this else condition work??
same This code work in login and registration page.
save in local file and run than it work :-
online code
Code
document.querySelector("#Profile_Save").addEventListener("click", () => {
if (document.querySelector("#Profile_Edit_Email").value.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)) {
document.querySelector("#Profile_Edit_Msg").classList.remove("active_success");
document.querySelector("#Profile_Edit_Msg").classList.remove("active_denger");
document.querySelector("#Profile_Save").innerHTML = "Loading...";
document.querySelector("#Profile_Save").classList.remove("active");
document.querySelector("#Profile_Save").disabled = true;
document.querySelector("#Profile_Edit_F_Name").disabled = true;
document.querySelector("#Profile_Edit_L_Name").disabled = true;
document.querySelector("#Profile_Edit_Email").disabled = true;
var f_name = document.querySelector("#Profile_Edit_F_Name").value,
l_name = document.querySelector("#Profile_Edit_L_Name").value,
email = document.querySelector("#Profile_Edit_Email").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "Api/ProfileEdit", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) { // this one if executing
var json = JSON.parse(xhr.responseText);
if (json.Status == "Ok") {
window.location.href = "Profile"; // it also work
} else {
document.querySelector("#Profile_Edit_Msg").classList.remove("active_success");
document.querySelector("#Profile_Edit_Msg").classList.add("active_denger");
document.querySelector("#Profile_Edit_Msg").innerHTML = json.Message;
}
} else { // this one else executing
document.querySelector("#Profile_Edit_Msg").classList.add("active_denger");
document.querySelector("#Profile_Edit_Msg").innerHTML = "Sorry, this content isn't available right now"; // this message show
}
}
xhr.send("F_Name=" + f_name + "&L_Name=" + l_name + "&Email=" + email);
document.querySelector("#Profile_Save").innerHTML = "Register";
document.querySelector("#Profile_Save").classList.add("active");
document.querySelector("#Profile_Save").disabled = false;
document.querySelector("#Profile_Edit_F_Name").disabled = false;
document.querySelector("#Profile_Edit_L_Name").disabled = false;
document.querySelector("#Profile_Edit_Email").disabled = false;
} else {
document.querySelector("#Profile_Edit_Msg").classList.add("active_denger");
document.querySelector("#Profile_Edit_Msg").innerHTML = "Invalid Email Address!";
}
});
return JSON
{"Status":"Ok","Message":"Profile Edit Successfully!"}
Output
open profile page and
error message:- "Sorry, this content isn't available right now"
help me!
Thank you!!
The readystatechange event fires multiple times.
Value State Description
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
Your
if (xhr.readyState == 4 && xhr.status == 200) {
branch will only be entered into at the end of a request, if the request was successful. But earlier, while the request is still ongoing, other state changes will occur, and the else branch will be entered into.
Instead, only do anything if the readyState is 4 - and, when it is 4, you can parse the response, or populate the #Profile_Edit_Msg to say there was a problem.
Other improvements:
Save the Profile_Edit_Msg in a variable instead of repetitively selecting it over and over again
Use strict equality, not sloppy equality
Use .textContent when assigning text to an element - only use .innerHTML when inserting HTML markup
JSON is a particular format of a string that can be deserialized into an object or other value. JSON.parse does not return JSON - JSON.parse is called with a JSON-formatted string and returns an object. Call your json variable something else.
denger looks misspelled - did you mean danger? (Typos are a common problem in programming - better to fix them earlier than later)
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
const profile = document.querySelector("#Profile_Edit_Msg");
if (xhr.status === 200) {
const result = JSON.parse(xhr.responseText);
if (result.Status === "Ok") {
window.location.href = "Profile";
} else {
profile.classList.remove("active_success");
profile.classList.add("active_denger");
profile.innerHTML = json.Message;
}
} else {
profile.classList.add("active_denger");
profile.textContent = "Sorry, this content isn't available right now";
}
};
You could also consider using the fetch API instead of XMLHttpRequest - fetch is a bit nicer to work with and has been supported in all modern browsers for ages.

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.

Ajax response in case of failing

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)

How to save AJAX response for later use [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I don't know how to implement getState. What I am trying to do is update a field on click with a state value returned in my AJAX call. I have seen a reference to promises in another response but I do not understand how to use them.
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var state = response.state;
}
}
$('#myState').on('click', function() {
var localState = getState();
$('#location').val(localState);
});
You need to change variable scope so it would be accessible from out of processRequest() function.
var response = '';
var state = '';
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
response = JSON.parse(xhr.responseText);
state = response.state;
}
}
$('#myState').on('click', function() {
$('#location').val(state);
});

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