XMLHttpRequest() not working in ff

Discussion in 'JavaScript' started by bogdanas, Aug 21, 2010.

  1. #1
    Hello, i have small piece of code that works perfectly in Chrome, but does not work in Firefox.
    	function loadXMLDoc()
    {
    var list='';
    if (window.XMLHttpRequest)
    {
      xmlhttp=new XMLHttpRequest();
      }
    else
      {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      
    xmlhttp.onreadystatechange=function()
      {
      console.log(xmlhttp.readyState);
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        list=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","http://www.domain.net/list.txt",false);
    xmlhttp.setRequestHeader("Content-Type", "text/plain"); 
    xmlhttp.send();
    console.log(list);
    return list;
    }
    
    Code (markup):
    in firefox 'list.txt' is downloaded perfectly but 'list' is empty variable.
     
    bogdanas, Aug 21, 2010 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    Okay so the false part of this line:
    xmlhttp.open("GET","http://www.domain.net/list.txt",false)
    is saying that you don't want to load the data asynchronously.
    This means that execution will halt until the data has been loaded...
    I am guessing that chrome is executing the 'onreadystatechange' function before the next lines of code where firefox isn't.
    Try:
    
    	function loadXMLDoc()
    {
    var list='';
    if (window.XMLHttpRequest)
    {
      xmlhttp=new XMLHttpRequest();
      }
    else
      {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    
    xmlhttp.open("GET","http://www.domain.net/list.txt",false);
    xmlhttp.setRequestHeader("Content-Type", "text/plain"); 
    xmlhttp.send();
    list=xmlhttp.responseText;
    console.log(list);
    return list;
    }
    
    Code (markup):
     
    camjohnson95, Aug 22, 2010 IP
  3. bogdanas

    bogdanas Peon

    Messages:
    17
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yup, that worked, thanks.
     
    bogdanas, Aug 22, 2010 IP
  4. dreteh

    dreteh Member

    Messages:
    514
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    33
    #4
    If you want to do ajax, I strongly recommend you use jquery. You just need to make a function call and it does everything for you.
     
    dreteh, Aug 22, 2010 IP