tags:

views:

33

answers:

3

Hi, I have a AJAX script which sends a POST request to PHP with some values. When I try to retrieve the values in PHP, am not able to get anything.

The AJAX script is

xmlhttp.open("POST","handle_data.php",true);
xmlhttp.setRequestHeader("Content-type","text/plain");
var cmdStr="cmd1=Commanda&cmd2=Command2";
xmlhttp.send(cmdStr);
alert(xmlhttp.responseText); 

The PHP script is

<?php
  echo $_POST['cmd1'];
?>

The output is just a plain empty alert box. Is there any mistake in the code?

A: 

You should not be grabbing the response immediately after sending the request. The reason is because the A in Ajax stands for Asynchronous, and that means the browser won't wait for your XMLHttpRequest to complete before it continues to execute your JavaScript code.

Instead you should write a callback that only runs when the response is fully ready. Just before your xmlhttp.send(cmdStr); call, add this:

xmlhttp.onreadystatechange = function()
{
    if (this.readyState == 4 && this.status == 200)
    {
        // This line is from your example's alert output
        alert(this.responseText);
    }
}
BoltClock
you should use `this` instead of `xmlhttp` within the anonymous function.
RobertPitt
@RobertPitt: thanks, I fixed my answer.
BoltClock
+3  A: 
xmlhttp.onreadystatechange = function()
{
    if(this.readyState == 4 && this.status == 200)
    {
        if(this.responseText != null)
        {
            alert(this.responseText);
        }
    };
}

You need to wait for the data to be received, use the onreadystatechange to delegate a callback.

http://www.w3.org/TR/XMLHttpRequest/

RobertPitt
Hi, I am getting an error message now.<code> <br /><b>Notice</b>: Undefined index: cmd1 in <b>C:\wamp\www\Filehand\handle_data.php</b> on line <b>2</b><br /></code>
Rajkumar
@Rajkumar: don't send a `text/plain` request header as it will mess up your Ajax request.
BoltClock
@BoltClock, Could you please tell me the right content type, if I have to send a String?
Rajkumar
Change your php code to `if(isset($_POST['cmd2'])) { echo $_POST['cmd2'];}`, Also look into php error_reporting.
RobertPitt
I have changed my content type and its working fine now.Thanks a lot friends.
Rajkumar
raj, that error was nothing to do with content-type, thats just for the javascript to know how to handle the data, e.g XML or json. the error you posted was php error, Glad your ok now.
RobertPitt
Thanks a ton, RobertPitt
Rajkumar
+1  A: 

I don't know if it is required, but might you want to use application/x-www-form-urlencoded as the request header.

Joel Kennedy
Its not required.
RobertPitt