0

I'm receiving through an AJAX GET request bytes series corresponding to an img. My ultimate goal is to convert these bytes into an image and to display it on the webpage (without refreshing). All the AJAX part is working perfectly, I'm receiving the data and had verified it through console log printing. But, when I'm trying to generate an html element with the raw data (in bytes, not the img yet), I does not work.

<script>
    $(document).ready(function(){
    
    setInterval(function(){
        $.ajax({
            type: 'GET',
            url : "/checkview",
            success: function(response){
                //console.log(response)
                let textC = response
                document.body.onload = addElement;
                function addElement() {
                // create a new div element
                const newDiv = document.createElement("div");

                // and give it some content
                const newContent = document.createTextNode(textC);

                // add the text node to the newly created div
                newDiv.appendChild(newContent);

                // add the newly created element and its content into the DOM
                const currentDiv = document.getElementById("div1");
                document.body.insertBefore(newDiv, currentDiv);
            },
            error: function(response){
                alert('An error occured')
            }
        });
    },10000);
    })
}
    </script>

Hints: the data are supposed to be in the textC variable.

So, I tried first to:

alert(textC);

which worked perfectly. I got data in bytes displayed. But, it works only when written in the setInterval function. I tried this same command in the console, this error appeared:

VM288:1 Uncaught ReferenceError: textC is not defined
    at <anonymous>:1:7

Therefore, I suppose there is a mistake in my code. Please help !

Marc Kch
  • 71
  • 5
  • `let textC = response` is declared inside a function, so it only exists in that function, so you can't access it from outside that function, hence the error. However, the `success` function is probably going to be called *after* the `onload` function, so the data wouldn't be available anyway. – Quentin Jan 23 '23 at 10:48
  • how can I define the variable outside the function then ? thanks for your answer ! – Marc Kch Jan 23 '23 at 10:51
  • You shouldn't. Instead, rethink your logic to trigger the creation of the elements from the success function. See also, the duplicate question. – Quentin Jan 23 '23 at 10:53
  • Yes, so I also proceed this way, but I doesn't work. I edited the script. May you take a look please ? – Marc Kch Jan 23 '23 at 10:56
  • You're still assuming the `success` function will run **after** the `load` event has fired. – Quentin Jan 23 '23 at 10:58
  • Also `document.body.onload` isn't a standard property so it will never trigger. – Quentin Jan 23 '23 at 10:58

0 Answers0