?
Solved

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

Posted on 2007-12-06
10
Medium Priority
?
822 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 1200 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
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
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
 
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 800 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Shows how to create a shortcut to site-search Experts Exchange using Google in the Chrome browser. This eliminates the need to type out site:experts-exchange.com whenever you want to search the site. Launch the Search Engine Menu: In chrome, via you…
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 +…
Suggested Courses

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