0

I am using XMLHttpRequest to read a text file uploaded to our website and add the text into an email. It always succeeds on the second run, but not the first. The readyState does not reach 4 until after the email is opened and closed, so the text appears the second time the email is opened. (sendEmail function runs when a button is pressed). I suspect when the email opens the second time, it is getting the first round of data. Is it possible to make this run on the first request?

    function sendEmail() {
        var greeting = "email greeting ";
        var email = "mailto:info@email.com";
        var subject = "?subject=Subject";
        var body = "&body=";

        var code = "some type of model code";

        getPartNumber(code);

        var pn = document.getElementById("part_number").innerHTML;

        window.location.href = email + subject + body + greeting + code + "." + "%0A" + pn;
    }

    function getPartNumber(code) {
        //file address is chosen based on what "code" is, but is a test file for now
        var file_address = "http://[address where file is located].txt";

        var data = new XMLHttpRequest();
        data.onreadystatechange = function () {
            if(data.readyState == 4 && data.status == 200) {
                document.getElementById("part_number").innerHTML = data.responseText;
            }
            //for debugging purposes
            //readyState reaches 2 and status reaches 200 first time email is opened
            //readyState reaches 4 and status reaches 200 after email is closed
            alert("ready state " + data.readyState + " status " + data.status);
        };

        data.open("GET", file_address, true);
        data.send(null);
    }
elsif
  • 1
  • 1

1 Answers1

0

Codes inside getPartNumber send an asynchronus request, so pn won't be the value you want . Try to use a callback function or Promise to handle this situation.