Rajkumar
Rajkumar

Reputation: 345

AJAX POST and PHP

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?

Upvotes: 0

Views: 187

Answers (3)

Joel Kennedy
Joel Kennedy

Reputation: 1611

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

Upvotes: 1

RobertPitt
RobertPitt

Reputation: 57268

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/

Upvotes: 3

BoltClock
BoltClock

Reputation: 723448

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);
    }
}

Upvotes: 0

Related Questions