1

I have js code like this :

function getData(){
    var url = "http://www.server.loc/?get=data"; /* resource */
    var xmlhttp = new XMLHttpRequest(); /* call XMLHttpRequest init */
    xmlhttp.open("GET", url,true);
    if(xmlhttp){
        xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4){ if(xmlhttp.status==200){
            /* success, then clear console */       
            return xmlhttp.responseText; /* return value is 'available' */
            } else {
            return "null";
            } } 
        }       
     }
     xmlhttp.send(null);
 }

 /* SHOW RESULT */
 var result = getData();
 console.log('result: '+result); /* result must "null" or "available" */

In web console print just show Result : undefined . How could that be? where is the code wrong?

Fredy
  • 2,840
  • 6
  • 29
  • 40
  • That's not exactly duplicate (because it uses jQuery) but concept still applies. When you perform an asynchronous request your function returns before request completes. Moreover getData returns nothing (return is inside anonymous function attached to onreadystatechange: its return value won't go anywhere. – Adriano Repetti Sep 11 '14 at 07:18
  • @AdrianoRepetti : so, what the solution? – Fredy Sep 11 '14 at 07:21
  • Pretty hard to give code sample in a comment and question is closed so I can't post...anyway: pass a function to getData() (with console.log() inside) and call it from within your anonymous function for onreadystatechange instead of returning. – Adriano Repetti Sep 11 '14 at 07:27
  • Take a look to [this page](http://vanilla-js.com/) in the section "Make an AJAX call", it compares jQuery (as in the other linked question) with "vanilla" JS (what you're doing). – Adriano Repetti Sep 11 '14 at 07:28
  • @AdrianoRepetti : can you sent me code sample to my email workfredy@gmail.com? Thank you – Fredy Sep 11 '14 at 07:33
  • no problem, sent! Happy coding! – Adriano Repetti Sep 11 '14 at 07:43

0 Answers0