Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with a function taken as a function parameter that takes AJAX as its own parameter

I can console.log(arg) but not arg.response. Curious what is the reason behind // edit: when I console log arg I can clearly see response property with data

   function doAjax(param, lambda) {
        let _xhttp = new XMLHttpRequest();
        _xhttp.open("GET", param, true);
        _xhttp.send();
        _xhttp.onload = lambda(_xhttp);
    }
    
    doAjax("ALL_FRAMES", function(arg) {
         console.log(arg.response); --> prints blank field in console
         //allFrames = JSON.parse(arg.response);
    });

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_xhttp.onload = lambda(_xhttp);

This means "call lambda(_xhttp) immediately, and then assign its return value to _xhttp.onload". You instead want to assign a function to onload, and that function will call lambda later on:

_xhtttp.onload = () => lambda(_xhttp);

// edit: when I console log arg I can clearly see response property with data

That is just a quirk of the way the dev tools handle logging objects. When logging an object, the object is not evaluated until you click on the object in your dev tools. So at the time the console.log ran it didn’t have the response yet, but by the time you click, it does have it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading