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
Solved

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

Posted on 2007-12-06
10
816 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

#Citrix #Internet Explorer #Enterprise Mode #IE 11 #IE 8
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
This Micro Tutorial will demonstrate how to add subdomains to your content reports. This can be very importing in having a site with multiple subdomains.

840 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