Solved

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

Posted on 2007-12-06
10
811 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
ID: 20421287
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
ID: 20421347
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
ID: 20421814
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
ID: 20421839
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
ID: 20421905
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 12

Expert Comment

by:Sinoj Sebastian
ID: 20421982
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
ID: 20421989
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
ID: 20422001
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
ID: 20422013
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
ID: 20422211
Ah, the strong, silent type, eh? No worries - glad to help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I annotated my article on ransomware somewhat extensively, but I keep adding new references and wanted to put a link to the reference library.  Despite all the reference tools I have on hand, it was not easy to find a way to do this easily. I finall…
SSL stands for “Secure Sockets Layer” and an SSL certificate is a critical component to keeping your website safe, secured, and compliant. Any ecommerce website must have an SSL certificate to ensure the safe handling of sensitive information like…
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.
This Micro Tutorial will demonstrate how nuggets on the Web are formatted by using Chrome Developer Tools. These tools would not only view the site's CSS but it can also modify it and save the CSS to use on your own site.

911 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

23 Experts available now in Live!

Get 1:1 Help Now