Solved

How do I get synchronous AJAX responseText to work with Firefox?

Posted on 2007-12-06
10
809 Views
Last Modified: 2013-12-07
I'm having a problem getting AJAX to work in Firefox when running as synchronous. Below is my function. I need it to run synchronous and return the body of an HTML page. It works fine in IE but nothing works in Firefox. Can someone help me?

function callAjax(url, params, method, async, getResponse)
{
      var xmlHttp;

      try
      {    
            //Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
            xmlHttp.overrideMimeType('text/html');
      }
        catch (e)
          {    
            //Internet Explorer  
            var XMLHTTP_IDS = new Array(
                  'MSXML2.XMLHTTP.5.0',
                  'MSXML2.XMLHTTP.4.0',
                  'MSXML2.XMLHTTP.3.0',
                  'MSXML2.XMLHTTP',
                  'Microsoft.XMLHTTP');
            var success = false;
            for (var i=0; i < XMLHTTP_IDS.length && !success; i++)
            {
                  try
                  {
                        xmlHttp = new ActiveXObject(XMLHTTP_IDS[i]);
                        success = true;
                  }
                  catch (e) {}
            }  

            if (!success || typeof(xmlHttp) == "undefined")
            {
                  alert("Your browser does not support AJAX!");        
                  return false;
            }
      }      

      //Get parameters
      var parameters = "";
      for(var i in params)
      {
            if (typeof(params[i]) == "undefined")
                  params[i] = "";

            var temp = params[i].toString().replace(/(\r\n|\r|\n)|^\s+|\s+$/g, "");            
            parameters += "&" + i + "=" + encodeURI(temp);
      }

      //Handle response and failures
      var response;
      xmlHttp.onreadystatechange = function()
      {      
            if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
            {            
                  if(xmlHttp.status == 200)
                        response = xmlHttp.responseText;
                  else
                  {
                        //Error response, ie. 404
                  }
            }
            else
            {
                  //waiting
            }
      };

      //Fire ajax
      url = url + '?nocache=' + Math.random() + parameters;
      xmlHttp.open(method, url, async);
      xmlHttp.send(null);

      //Return results
      if(getResponse == true)
      {
            if (typeof(response) == "undefined")
                  response = "";
            return response;
      }
}
0
Comment
Question by:bemara57
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 19

Expert Comment

by:erikTsomik
Comment Utility
try may be adding this piece of code which supposed to work for all types of browsers

if (window.XMLHttpRequest)// Mozilla, Safari, ...

    {
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType )
        {
            httpRequest.overrideMimeType('text/xml');
            // See note below about this line
        }
    }
    else if (window.ActiveXObject)// IE
    {
        try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {}
        }
    }

    if (!httpRequest)
    {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
0
 
LVL 29

Accepted Solution

by:
Badotz earned 300 total points
Comment Utility
The 3rd parameter, >>async<<

xmlHttp.open(method, url, async);

should be false.

Also, you blindly declare a callback function - not needed for synchronous calls.
0
 

Author Comment

by:bemara57
Comment Utility
You mean aync should be true for it to work right? Should I do something like this for the callback function (keeping in mind this is supposed to work with IE and Firefox):

var response;
if (async)
{
      response = xmlHttp.responseText;
}
else
{
      //Handle response and failures      
      xmlHttp.onreadystatechange = function()
      {      
            if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
            {            
                  if(xmlHttp.status == 200)
                        response = xmlHttp.responseText;
                  else
                  {
                        //Error response, ie. 404
                  }
            }
            else
            {
                  //waiting
            }
      };
}
0
 
LVL 29

Expert Comment

by:Badotz
Comment Utility
No, I mean that the third parameter should be FALSE. You asked how to establish a SYNCHRONOUS connection.

You said:

"I need it to run synchronous and return the body of an HTML page."
0
 

Author Comment

by:bemara57
Comment Utility
Yes I understand that I need to make it false if I need it to work synchronously, but what I'm saying that my function doesn't work with Firefox if running synchronous. Asynchronous works fine.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 12

Expert Comment

by:Sinoj Sebastian
Comment Utility
Try this

instead of

//Fire ajax
      url = url + '?nocache=' + Math.random() + parameters;
      xmlHttp.open(method, url, async);
      xmlHttp.send(null);

      //Return results
      if(getResponse == true)
      {
            if (typeof(response) == "undefined")
                  response = "";
            return response;
      }

use

//Fire ajax
      url = url + '?nocache=' + Math.random() + parameters;
      xmlHttp.open(method, url, async);
      xmlHttp.send(null);

      //Return results
      if(async) return xmlHttp.responseText;

      if(getResponse == true)
      {
            if (typeof(response) == "undefined")
                  response = "";
            return response;
      }
0
 
LVL 29

Expert Comment

by:Badotz
Comment Utility
Then something else is wrong.
var xobj = getXmlHttp();
 

if (xobj == null)

{

	alert('error: XMLHttpRequest not supported');

	return null;

}
 

xobj.open('POST', url, false);

xobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xobj.setRequestHeader('Connection', 'close');

		

xobj.send(job);
 

if (!async) { return xobj.responseText; }

Open in new window

0
 
LVL 12

Expert Comment

by:Sinoj Sebastian
Comment Utility
oops
use

//Fire ajax
      url = url + '?nocache=' + Math.random() + parameters;
      xmlHttp.open(method, url, async);
      xmlHttp.send(null);

      //Return results
      if(!async) return xmlHttp.responseText;

      if(getResponse == true)
      {
            if (typeof(response) == "undefined")
                  response = "";
            return response;
      }
0
 
LVL 12

Assisted Solution

by:Sinoj Sebastian
Sinoj Sebastian earned 200 total points
Comment Utility
full code
function callAjax(url, params, method, async, getResponse)

{

      var xmlHttp;
 

      try

      {    

            //Firefox, Opera 8.0+, Safari

            xmlHttp = new XMLHttpRequest();

            xmlHttp.overrideMimeType('text/html');

      }

        catch (e)

          {    

            //Internet Explorer  

            var XMLHTTP_IDS = new Array(

                  'MSXML2.XMLHTTP.5.0',

                  'MSXML2.XMLHTTP.4.0',

                  'MSXML2.XMLHTTP.3.0',

                  'MSXML2.XMLHTTP',

                  'Microsoft.XMLHTTP');

            var success = false;

            for (var i=0; i < XMLHTTP_IDS.length && !success; i++)

            {

                  try

                  {

                        xmlHttp = new ActiveXObject(XMLHTTP_IDS[i]);

                        success = true;

                  }

                  catch (e) {}

            }  
 

            if (!success || typeof(xmlHttp) == "undefined")

            {

                  alert("Your browser does not support AJAX!");        

                  return false;

            }

      }      
 

      //Get parameters

      var parameters = "";

      for(var i in params)

      {

            if (typeof(params[i]) == "undefined")

                  params[i] = "";
 

            var temp = params[i].toString().replace(/(\r\n|\r|\n)|^\s+|\s+$/g, "");            

            parameters += "&" + i + "=" + encodeURI(temp);

      }
 

      //Handle response and failures

      var response;

      xmlHttp.onreadystatechange = function()

      {      

            if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")

            {            

                  if(xmlHttp.status == 200)

                        response = xmlHttp.responseText;

                  else

                  {

                        //Error response, ie. 404

                  }

            }

            else

            {

                  //waiting

            }

      };
 

      //Fire ajax

      url = url + '?nocache=' + Math.random() + parameters;

      xmlHttp.open(method, url, async);

      xmlHttp.send(null);
 

      //Return results

      if(!async) return xmlHttp.responseText;
 

      if(getResponse == true)

      {

            if (typeof(response) == "undefined")

                  response = "";

            return response;

      }

}

Open in new window

0
 
LVL 29

Expert Comment

by:Badotz
Comment Utility
Ah, the strong, silent type, eh? No worries - glad to help.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Google currently has a new report that is in beta and coming soon to Webmaster Tool accounts. This Micro Tutorial will highlight new features for Google Webmaster Tools.
How to create a custom search shortcut to site-search Experts Exchange using Google in the Firefox browser. This eliminates the need to type out site:experts-exchange.com whenever you want to search the site. Launch your Bookmark Menu: Press 'Ctrl +…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now