views:

145

answers:

4
var url="display.php?vote="+grade; 
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
 } 
}

This piece of code fails to send out the request. How to create a xmlHttp correctly?

A: 

Here is a "80%" solution.

function GetXHR()
{
  try
  {
    if (window.XmlHTTPRequest)
      xmlHttp = new XmlHTTPRequest()
    else
      xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0")
  }
  catch(e) { }
}

var xmlHttp = GetXHR()
if (xmlHttp)
{
    // Proceed with xmlHttp usage.
}

Edit

Note I tend to avoid the old ProgID "Microsoft.XMLHTTP" in favour of the one I have used because this later ProgID has a more predictable behaviour and is ever so slightly more secure. However if you want wider compatiblity with really old Windows machines (I'm talking out-of-support stuff) then you could use the older one in your specific case.

AnthonyWJones
What's the 100% solution?
Mask
Using `jQuery.ajax()`.
BalusC
@Mask: Actually its more like 99% but I'm refering to the "80/20" rule. This small chunk of code (the 20% of effort) solves the problem for the vast majority of cases (the 80%). In fact it will work on all common browsers. It would fail on say a vanilla Windows 95 machine running IE5.
AnthonyWJones
A: 

The relative URL might be wrong as opposed to the current context. Hard to say based on the as far posted information. You need to investigate the XHR status for more details.

At least, w3schools.com has a nice basic Ajax tutorial. After understanding how Ajax/Javascript works under the hood I'd recommend you to continue with jQuery, it takes all the nasty browser specific work from your hands.

Good luck.

BalusC
+1  A: 
<script type="text/javascript">
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else
  {
  alert("Your browser does not support XMLHTTP!");
  }
}
</script>

this piece of code is available in link text you can learn basics here like i did. hope this helps.

tony_le_montana
A: 

var xmlHttp=new(window.ActiveXObject?ActiveXObject:XMLHttpRequest)('Microsoft.XMLHTTP');

antimatter15