PHP and Ajax POST Request

codeguardian's Avatar
Light Poster
I am trying to send a post request to PHP with Ajax. But, I never get the data with $_POST command. I am wondering what is going on. The code i used is below:

.html
--------------------------------
HTML Code:
<html>
<head>
        
 <title>Untitled</title>

<SCRIPT>

function postForm() {
  var xmlHttp;
  try
    {    // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {    // Internet Explorer    
      try
      {
       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
      } catch (e)
        {      
         try
         {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e)
           {       
             alert("ERROR: CAN NOT POST DATA");
           }
        }
    }
    
    try 
    {
      xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {
         alert(xmlHttp.responseText);
        }
      }
       xmlHttp.open("POST","temp2.php",true);
       postStr = "name="+escape(myForm.name.value);
       alert("SENDING: "+postStr);
       xmlHttp.setRequestHeader("Content-Type","application-x-www-form-urlencoded");
       xmlHttp.send(postStr);
    } catch(e)
      {
       alert("ERROR POSTING DATA");
      } 

}

</SCRIPT>

</head>
<body>

<FORM METHOD="post" NAME="myForm" onsubmit="postForm()">
<INPUT NAME="name" TYPE="text"><BR>
<INPUT NAME="pass" TYPE="text"><BR>
<INPUT TYPE="submit" VALUE="login">
</FORM>

</body>
</html>

------------------------------------------------
THen i try to get the data by:

<?

echo "NAME: ".$_POST['name']."<BR>\n";
echo "NAME: ".$_GET['name']."<BR>\n";
echo "NAME: ".$_REQUST['name']."<BR>";


?>
None of the methods ($_POST,$_GET,or REQUEST) get the data. What am i doing wrong???

Last edited by shabbir; 26Dec2007 at 17:03.. Reason: Code block
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Practically there is no need to set the request header, and if you set it should look like this
Code: JavaScript
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
0
codeguardian's Avatar
Light Poster
Thank, it works!!!!! it dose not work with the header i used or without header.
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Use Prototype JS, http://www.go4expert.com/showthread.php?t=5541