Solved

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

Posted on 2007-12-06
10
815 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
disclaimer when opening internet 2 39
simple javascript form validation 2 20
Why doesn't Google directions work? 6 47
Jquery 10 20
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
I recently found myself in a Corporate Situation where the client had requested blocking access to any and all websites except his own Domain? Easy? I am sure this would be your answer but their requirement was, this has to be done without using…
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.
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…

821 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