3

i make a ajax request to a json string and then i parse it, i want to return this Json object called "encuesta" from event onreadystatechange to the "jacu" variable to access globally

heres my code:

window.onload= function(){
 enter code here`tabla = document.getElementById("pregunta");
 enter code here`jencu= ajax("GET","datos/encuesta.json",true,"lee")
 }

function ajax(metodo,url,bolean,que){
   var xhr;
   if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
   }else{ 
       xhr=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.onreadystatechange=function(){

           if (xhr.readyState==4 && xhr.status==200){
              if(que == "lee"){
                encuesta=xhr.responseText;
                  encuesta = JSON.parse(encuesta)
               }
           }
    }

   xhr.open(metodo,url,true);
   xhr.send();
}
LuisDavis
  • 145
  • 1
  • 6
  • can you explain what is not working as expected for you? – Matt Pileggi Feb 25 '14 at 20:27
  • i cant access to the json object globally @MattPileggi – LuisDavis Feb 25 '14 at 20:37
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) –  Sep 23 '14 at 03:49
  • Although JSON.parse working well for me it may not bad idea to try $.parseJSON(encuesta). – QMaster Dec 28 '18 at 12:05
  • My comment is not about the main issue but about the optimization logic. You have to put the statement if(que == "lee"){} to outside of the AJAX call and do this check BEFORE you do any call on AJAX. Why? Because you overload the CGI/PHP/whatever script with useless calls, when que != "lee". In other words: firstly check if que == "lee" and IF SO, proceed, if NOT - terminate with return (error or whatever die statement). – Arsenii Mar 06 '19 at 09:55

1 Answers1

0

If you want encuesta to be accessible globally, you should declare it outside your function.

Moritz Möller
  • 116
  • 1
  • 5
  • can you make me an example please? – LuisDavis Feb 25 '14 at 21:00
  • Just type var encuesta = ""; before your window.onload function. It is now a global variable, that is then overwritten (given the new value) in your onreadystatefunction and known in the rest of the code. – Moritz Möller Feb 25 '14 at 21:06