简体   繁体   中英

AJAX call to return values from PHP not working

I have a AJAX script which sends value to PHP script and to retrieve the value from the PHP script. The part where the script sends the value is working fine. Its the problem with the retrieving values. I am not able to figure out what is wrong.

AJAX code:

$(document).ready(function() {
    $("#raaagh").click(function() {
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data) {
                console.log(data);
                $.ajax({
                    url:'ajax.php',
                    data: data,
                    dataType:'json',
                    success:function(data1) {
                        var y1=data1;
                        console.log(data1);
                    }
                });
            }
        });
    });
});

PHP code:

<?php

$userAnswer = $_POST['name'];    

echo json_encode($userAnswer);    
?>
data: {name: 145}

尝试这种希望能奏效的方法。

Please check whether "name" is posted before assigning the value to $userAnswer.

Both ajax scripts are sending to "ajax.php". In first ajax request "name" is posted, but in 2nd ajax request "name" is not posted.

To see warnings and errors, enable error reporting in php.

<?php 
//To enable error reporting
ini_set('display_errors',true);
error_reporting(E_ALL);

Set type:'POST' inside the second ajax call and try to use data1[0] .
Also remember that you are sending a json string (that comes from the first ajax) with the second request.
Basically you are encoding an encoded value,so when you receive the post value you should json_decode the post value

Your nested AJAX call does not have the request type specified. The default is GET but your ajax.php is trying to find a POST.

$(document).ready(function() {
$("#raaagh").click(function() {
    $.ajax({
        url: 'ajax.php',
        type: "POST",
        data: ({name: 145}),
        success: function(data) {
            console.log(data);
            $.ajax({
                url:'ajax.php',
                type: "POST",       //<-- added here
                data: {name:data},  //<-- also required for POST
                dataType:'json',
                success:function(data1) {
                    var y1=data1;
                    console.log(data1);
                }
            });
        }
    });
});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM