0

Not sure what I am doing wrong here.

HTML

<form id="inp" onsubmit="process()">
    <input id="link" type="text" name="link" placeholder="Enter your link">
    <input id="submit" type="submit" name="submit" value="&rarr;">
</form>

JavaScript

    function createRequest() {
        let result = null;
        if (window.XMLHttpRequest) {
            result = new XMLHttpRequest();
            result.overrideMimeType('application/json');
        }
        else {
            window.alert("Abort!");
        }
        return result;
    }

    let c=0;
    function process() {
        let l = document.getElementById("inp").link.value;
        let resp;
        let req = createRequest();
        let payload = {
            link: l,
            ignoreException: true
        };
        req.open("POST", url, true);
        req.setRequestHeader("Content-Type", "application/json");
        req.send(payload);
        req.onreadystatechange = function () {
            if (req.readyState === 4 && req.status === 200) {
                resp = req.responseText;
                console.log("response text - " + resp);
            }
            console.log(req.readyState + " " + req.status + " " + c);
        };
    }

I want it to log the readyState and status for every state change and also log the response text for the final state.

It logs " 4 0 1 " which means it's changing the state just once and is changing it straight to the final state.

It should change the states as .open(), .setRequestHeader(), and .send() functions are executed.

How can I make this work?

Note- "url" parameter is the api url.

1 Answer 1

1

If you want the onreadystatechange event to be called for .open() and .setRequestHeader() you will need to register the onreadystatechange event handler before you call the open() and setRequestHeader() functions.

So if you move the onreadystatechange definition up a few lines, it should be good.

So something like this:

    function process() {
    let l = document.getElementById("inp").link.value;
    let resp;
    let req = createRequest();
    let payload = {
        link: l,
        ignoreException: true
    };
    req.onreadystatechange = function () {
        if (req.readyState === 4 && req.status === 200) {
            resp = req.responseText;
            console.log("response text - " + resp);
        }
        console.log(req.readyState + " " + req.status + " " + c);
    };
    req.open("POST", url, true);
    req.setRequestHeader("Content-Type", "application/json");
    req.send(payload);

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.