Home > Back-end >  executing if and else both condition in JavaScript
executing if and else both condition in JavaScript

Time:06-13

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??

  • save in local file and run than it work :- enter image description here

    help me! Thank you!!

    CodePudding user response:

    onreadystatechange event is fired for all the statuses mentioned in that link. In your case, you will need to check when status equals 4(i.e, when the operation is complete and response is sent back to the browser). So, you can amend your code block like below:

    xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4) {  
                        if(xhr.status == 200){
                            var json = JSON.parse(xhr.responseText);
                            if (json.Status == "Ok") {
                                window.location.href = "Profile";  
                            } 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{
                             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 
                        }
                        
                    }
                };
    

    CodePudding user response:

    Try this one

    if (xhr.readyState != 4 && xhr.status != 200) {
                        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 
                    }else if (xhr.readyState == 4 && xhr.status == 200) {
                        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;
                        }
                    }

  • Related