Forum Moderators: open

Message Too Old, No Replies

AJAX Nothing Returned

         

webfoo

5:32 pm on Jun 22, 2010 (gmt 0)

10+ Year Member



Hello Folks,

Having some trouble getting this AJAX to submit a POST request to retrieve the data. Is there anything wrong with this code?

Regards,
Webfoo

<html>
<head>
<script language="Javascript">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("POST","https://subdomain.example.com/directory/index.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(escape("parameter1=value1&parameter2=value2"));

alert(xmlhttp.responseText);


</script>

<title>title</title>
</head>

<body>

</body>
</html>

Fotiman

8:01 pm on Jun 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



xmlhttp.open("POST","https://subdomain.example.com/directory/index.php",true);

You are creating an asynchronous request, which means that you need to attach an onreadystatechange event handler in order to access the response data. Where you are calling alert, there's no guarantee that the request has even made it to the server yet.

Also note, you should probably use encodeURIComponent on the individual parameter values instead of escaping the whole string.

Also, the language attribute is invalid, so don't include it. Use type="text/javascript" instead.

Also, you're creating a global variable xmlhttp. You should, at the very least, declare it using var.


<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","https://subdomain.example.com/directory/index.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.responseText);
}
};
xmlhttp.send("parameter1=" + encodeURIComponent(value1) +
"&parameter2=" + encodeURIComponent(value2) );
</script>

curiousplayer2003

7:54 am on Jun 28, 2010 (gmt 0)

10+ Year Member



You can also refer this webpage to get a clear idea on AJAX
[mistonline.in...]