无法获得正确的返回数据

What is wrong:

$('#btnSend').click(function()
{     
    var msg = $('#txtar').val();  // textarea
    alert (msg); // works well, for example 'abc'
    $.ajax(
    {
        type: "POST",
        url: "write.php",
        data: {msg: msg},
        success: function(r)
        {
            alert(r); // doesn't work
        }
    });
});

write.php:

$a = $_POST['msg'];
echo $a;

Instead of abc I get the content of whole write.php file in the alert.

Does write.php contain opening and closing php tags:

<?php
$a = $_POST['msg'];
echo $a;
?>

Seems like your write.php file does not contain <?php. Add it at the beginnig. The closing ?> is optional.

try this:

alert(r.msg);

or

alert(r->msg);

Thats very simple...

write.php

 $a = $_POST['msg'];
 echo $a;
 exit;

put exit or end here or else the code will move further unnecessarily.

  • php5 doesn't need closing php tags if its a file with only php

Also here's a small example. Just tested this on an apache2.4 server with libapache2-mod-php5. If PHP code works otherwise though, don't worry about your server, or the config, just make sure you're including a JS library to make those AJAX requests work.

PHP(5)

<?php
if($_POST && isset($_POST['payload'])) {
     echo "hello ".$_POST['payload'];
}

JS

$.ajax({
    type: "POST",
    url: "this.php",
    data: {payload:"world"},
    success: function(response){ alert(response); }
});