最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to return data from an AJAX post from PHP? - Stack Overflow

programmeradmin1浏览0评论

I am trying to return values from $.post, and am getting nowhere. Here are the code snippets:

<!-- language: lang-js -->

$(document).ready(function(){
$('.d1').dblclick(function() {
    $(this).css("background-color","blue");
    var datas =  $(this).attr('id');

    $.post(

            "simpleData.php",
            {"chess":datas},
            {dataType: "JSON"},
            {async:false},
            {contentType: "application/json; charset=utf-8"},
              {success: function(msg){
                 alert(msg.d);
                 var resultAsString = msg.d;
                 document.write(resultAsString);
    }

          });       
    });

});

Here is the division for the output. I receive no output here:

<!-- language: lang-php -->    

<div id = "output">
<?php
echo "This is the default output <br />";


echo $_REQUEST['chess'];

?>                      

<?php

print_r($_REQUEST);

?> 

Here is the php program that is being called (simpleData.php):

<!-- language: lang-php -->

<html>
<body
<?php
$move_from = $_REQUEST['chess'];
var_dump($_REQUEST);
echo "this is move_from  $move_from";
?>

</body>
</html>

I receive the correct output from this, but it never appears in the div. Also, I receive no output from the alert.

Help and advice, please.

Here is updated code which, regrettably still does not work. The result appears in the div, but all it says is "undefined". Additionally, the chessboard which is on the page is wiped out.

<script type="text/javascript">

$.ajaxSetup ({  
    cache: false  
});  

$(document).ready(function(){
    $('.d1').dblclick(function() {
        $(this).css("background-color","blue");
        var datas =  $(this).attr('id');

$.post("simpleData.php", {
            data: {"chess":datas},
            dataType: "json",
            async:false,
            contentType: "application/json; charset=utf-8",
            header: "HTTP/1.1 200 OK",
            success: function(html){
               var resultAsString = html;
               $("#output").html(resultAsString);      
              document.write(resultAsString);
            }    
});


</script>

Here is the program [simpleData.php] that is called:

<html>
<body

 <?php
$move_from = $_REQUEST['chess'];
var_dump($_REQUEST);
echo "this is move_from  $move_from";

?>

</body>
</html>

Here is the html output from the Firebug:

Notice: Undefined index: chess in /var/www/simpleData.php on line 12 array(6) { ["data"]=> array(1) { ["chess"]=> string(2) "e8" } ["dataType"]=> string(4) "json" ["async"]=> string(5) "false" ["contentType"]=> string(31) "application/json; charset=utf-8" ["header"]=> string(15) "HTTP/1.1 200 OK" ["success"]=> string(9) "undefined" } this is move_from

Help and advice, please. Thanks

This is the most recent code:

<script type="text/javascript">

$.ajaxSetup ({  
cache: false  
});  

$(document).ready(function(){
$('.d1').dblclick(function() {
    $(this).css("background-color","blue");
    var datas =  $(this).attr('id');

$.post("simpleData.php", {
        data: {"chess":datas},
        dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        header: "HTTP/1.1 200 OK",
        success: function(html){
           newProcessData(html);
        }

        });

    }); 
});

function newProcessData(html){
    var resultAsString = html;
    $("#output").html(resultAsString);
    document.write(resultAsString);
    alert("yippee");
}

Here is the program that is called (simpleData.php)[it has not changed]

<html>
 <body>
<?php
$move_from = $_REQUEST['chess'];
var_dump($_REQUEST);
echo "this is move_from  $move_from";
?>

</body>
</html>

I know that the code reached the function newProcessData, since the alert is shown.

Here is the output from Firebug:

Headers:

Date    Mon, 22 Aug 2011 04:01:42 GMT
Server  Apache/2.2.19 (Debian)
X-Powered-By    PHP/5.3.7-1
Vary    Accept-Encoding
Content-Encoding    gzip
Content-Length  401
Keep-Alive  timeout=15, max=99
Connection  Keep-Alive
Content-Type    text/html
Request Headersview source
Host    localhost
User-Agent  Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0 Iceweasel/6.0
Accept  */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost/jq3_test.php
Content-Length  137
Pragma  no-cache
Cache-Control   no-cache

POST:

async   false
contentType application/json; charset=utf-8
dataType    json
data[chess] e8
header  HTTP/1.1 200 OK
success undefined
Source
data%5Bchess%5D=e8&dataType=json&async=false&contentType=application%2Fjson%3B+charset%3Dutf-8&header=HTTP%2F1.1+200+OK&success=undefined

HTML:

Notice: Undefined index: datas in /var/www/simpleData.php on line 13 array(6) { ["data"]=> array(1) { ["chess"]=> string(2) "e8" } ["dataType"]=> string(4) "json" ["async"]=> string(5) "false" ["contentType"]=> string(31) "application/json; charset=utf-8" ["header"]=> string(15) "HTTP/1.1 200 OK" ["success"]=> string(9) "undefined" } this is move_from

Any help that can be rendered will be DEEPLY appreciated Thanks

I am trying to return values from $.post, and am getting nowhere. Here are the code snippets:

<!-- language: lang-js -->

$(document).ready(function(){
$('.d1').dblclick(function() {
    $(this).css("background-color","blue");
    var datas =  $(this).attr('id');

    $.post(

            "simpleData.php",
            {"chess":datas},
            {dataType: "JSON"},
            {async:false},
            {contentType: "application/json; charset=utf-8"},
              {success: function(msg){
                 alert(msg.d);
                 var resultAsString = msg.d;
                 document.write(resultAsString);
    }

          });       
    });

});

Here is the division for the output. I receive no output here:

<!-- language: lang-php -->    

<div id = "output">
<?php
echo "This is the default output <br />";


echo $_REQUEST['chess'];

?>                      

<?php

print_r($_REQUEST);

?> 

Here is the php program that is being called (simpleData.php):

<!-- language: lang-php -->

<html>
<body
<?php
$move_from = $_REQUEST['chess'];
var_dump($_REQUEST);
echo "this is move_from  $move_from";
?>

</body>
</html>

I receive the correct output from this, but it never appears in the div. Also, I receive no output from the alert.

Help and advice, please.

Here is updated code which, regrettably still does not work. The result appears in the div, but all it says is "undefined". Additionally, the chessboard which is on the page is wiped out.

<script type="text/javascript">

$.ajaxSetup ({  
    cache: false  
});  

$(document).ready(function(){
    $('.d1').dblclick(function() {
        $(this).css("background-color","blue");
        var datas =  $(this).attr('id');

$.post("simpleData.php", {
            data: {"chess":datas},
            dataType: "json",
            async:false,
            contentType: "application/json; charset=utf-8",
            header: "HTTP/1.1 200 OK",
            success: function(html){
               var resultAsString = html;
               $("#output").html(resultAsString);      
              document.write(resultAsString);
            }    
});


</script>

Here is the program [simpleData.php] that is called:

<html>
<body

 <?php
$move_from = $_REQUEST['chess'];
var_dump($_REQUEST);
echo "this is move_from  $move_from";

?>

</body>
</html>

Here is the html output from the Firebug:

Notice: Undefined index: chess in /var/www/simpleData.php on line 12 array(6) { ["data"]=> array(1) { ["chess"]=> string(2) "e8" } ["dataType"]=> string(4) "json" ["async"]=> string(5) "false" ["contentType"]=> string(31) "application/json; charset=utf-8" ["header"]=> string(15) "HTTP/1.1 200 OK" ["success"]=> string(9) "undefined" } this is move_from

Help and advice, please. Thanks

This is the most recent code:

<script type="text/javascript">

$.ajaxSetup ({  
cache: false  
});  

$(document).ready(function(){
$('.d1').dblclick(function() {
    $(this).css("background-color","blue");
    var datas =  $(this).attr('id');

$.post("simpleData.php", {
        data: {"chess":datas},
        dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        header: "HTTP/1.1 200 OK",
        success: function(html){
           newProcessData(html);
        }

        });

    }); 
});

function newProcessData(html){
    var resultAsString = html;
    $("#output").html(resultAsString);
    document.write(resultAsString);
    alert("yippee");
}

Here is the program that is called (simpleData.php)[it has not changed]

<html>
 <body>
<?php
$move_from = $_REQUEST['chess'];
var_dump($_REQUEST);
echo "this is move_from  $move_from";
?>

</body>
</html>

I know that the code reached the function newProcessData, since the alert is shown.

Here is the output from Firebug:

Headers:

Date    Mon, 22 Aug 2011 04:01:42 GMT
Server  Apache/2.2.19 (Debian)
X-Powered-By    PHP/5.3.7-1
Vary    Accept-Encoding
Content-Encoding    gzip
Content-Length  401
Keep-Alive  timeout=15, max=99
Connection  Keep-Alive
Content-Type    text/html
Request Headersview source
Host    localhost
User-Agent  Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0 Iceweasel/6.0
Accept  */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost/jq3_test.php
Content-Length  137
Pragma  no-cache
Cache-Control   no-cache

POST:

async   false
contentType application/json; charset=utf-8
dataType    json
data[chess] e8
header  HTTP/1.1 200 OK
success undefined
Source
data%5Bchess%5D=e8&dataType=json&async=false&contentType=application%2Fjson%3B+charset%3Dutf-8&header=HTTP%2F1.1+200+OK&success=undefined

HTML:

Notice: Undefined index: datas in /var/www/simpleData.php on line 13 array(6) { ["data"]=> array(1) { ["chess"]=> string(2) "e8" } ["dataType"]=> string(4) "json" ["async"]=> string(5) "false" ["contentType"]=> string(31) "application/json; charset=utf-8" ["header"]=> string(15) "HTTP/1.1 200 OK" ["success"]=> string(9) "undefined" } this is move_from

Any help that can be rendered will be DEEPLY appreciated Thanks

Share Improve this question edited Aug 7, 2012 at 18:58 Factor Mystic 26.8k16 gold badges81 silver badges96 bronze badges asked Aug 18, 2011 at 21:55 Woffy613Woffy613 211 silver badge5 bronze badges 1
  • 1 (seeing your other question asking to answer this question) if you post a very long question it will be very difficult for us to read and understand, and answer. Try to be concise. – Nivas Commented Aug 21, 2011 at 6:29
Add a ment  | 

5 Answers 5

Reset to default 2

You can refer to the official jquery documentation for nice simple examples of posting to php and updating div's:

http://api.jquery./jQuery.post/

such as:

$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

this might not be the plete reason why, but when jQuery asks for dataType:'json' which by the way the manual shows as lowercase, not upper case (not sure if it matters) -- the PHP needs to identify the output as json with headers (and also return an OK status) like so:

header("HTTP/1.1 200 OK");
header('Content-type: application/json');

before you echo any data.

Also don't return html tags, just call the json headers, echo output, then exit().

Oh and the array needs to be encoded to JSON:

echo json_encode($_REQUEST['chess']);

EDITS: I think you may have put some of this advice in the wrong places - try this. Your simpleData.php from beginning to end, should look like this to return JSON data:

<?php
header("HTTP/1.1 200 OK");
header('Content-type: application/json');
echo json_encode($_REQUEST);
exit();
?>

Note the lack of surrounding HTML tags or anything outside of the php tags. You cannot have it both ways, a script that returns HTML for debugging and a script that returns proper JSON that won't break the jQuery post.

If you want to see the JSON response of simpleData.php while looking at the HTML page making the post, install a tool like the firebug plugin for firefox, and watch the NET panel to be able to inspect exactly what is happening on the post.

Now, remove the header content type stuff from your javascript, that was added in the wrong place:

$.post("simpleData.php", {
        data: {"chess":datas},
        dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        header: "HTTP/1.1 200 OK",
        success: function(html){
           newProcessData(html);
        }

        });

should bee:

$.post("simpleData.php", {
        data: {"chess":datas},
        dataType: "json",
        async:false,
        success: function(html){
           newProcessData(html);
        }

        });

I think your needs to be in the original file, not the .php file.

{success: function(msg){
                 alert(msg.d);
                 var resultAsString = msg.d;
                 //document.write(resultAsString);
                 $("#output").html(resultAsString); //this will add it to the div
    }
$.post("simpleData.php", {
            data: {chess:datas},
            dataType: "html",
            async:false,
            success: function(html){
               alert(html);
               var resultAsString = html;
               document.write(resultAsString);
            }    
});

Your syntax is a bit strange, try the version above (though to be honest, document.write shouldn't be used normally).

I am not a PHP programmer but based on the following output that you provided


["data"]=> array(1) { ["chess"]=> string(2) "e8" } 

It looks like the "chess" data is still within "data" in $_REQUEST. You should try doing $_REQUEST['data']['chess'] instead and see if that would work.

发布评论

评论列表(0)

  1. 暂无评论