douyeyan0650
2016-07-27 12:30
浏览 38

jQuery AJAX没有得到PHP的响应

I used to be able to make jQuery AJAX requests perfectly well in NodeJS, but when I try to do the same in PHP, I have several issues. Nothing I could find in SO could help, so I'd like to ask, what's the problem with my simple example?

index.php - really isn't much, only loading 2 JS, 1 PHP and defining a button and a paragraph.

<html>
    <head>
        <script src='jquery-3.0.0.js'></script>
        <script src='main_js.js'></script>      
    </head>
    <body>
        <button id="action" onClick="Send()">Send data</button>
        <p id="result">Lorem ipsum</p>

        <?php require('main_php.php'); ?>                   
    </body>
</html>

main_js.js - it contains the function associated to the 'onClick' event.

function Send(){
    var data_JSON = {
        input: "test",
        message: "Sending..."
    };          
    $.ajax({
        url: 'main_php.php',
        type: 'POST',
        data: data_JSON,
        contentType: 'application/json',
        success: function(data){                
            alert(data);                
            document.getElementById("result").innerHTML = "DONE!";          
        }       
    }); 

} 

main_php.php - it listens to POST requests, theoretically, and sends back a JSON with echo. Again, theoretically...

<?php
if ($_POST){        
    // Make a array with the values
    $vals = array(
        'input'     => $input,
        'message'   => $message
    );      
    echo json_encode($vals, JSON_PRETTY_PRINT);     // Now we want to JSON encode these values to send them to $.ajax success.
    exit;                                           // to make sure you aren't getting nothing else
}
?>

jQuery AJAX's success function runs, as the text "DONE!" appears in the paragraph, but the alert message is entirely empty. alert(data.input) (and same for message) shows undefined.

It is clear that no data is sent back to the AJAX request. How can I fix it?

Note: it is the entirety of the code, there's nothing else shown, and I also shortened and simplified as much as possible.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongmaonao0505 2016-07-27 12:37
    已采纳

    That's because you're not sending response from PHP as JSON.

    Add following line above echo json_encode();

    header('Content-Type: application/json');
    

    So your PHP code will look something like this,

    <?php
    if ($_POST){        
        // Make a array with the values
        $vals = array(
            'input'     => $input,
            'message'   => $message
        );
        header('Content-Type: application/json');      
        echo json_encode($vals, JSON_PRETTY_PRINT);     // Now we want to JSON encode these values to send them to $.ajax success.
        exit;                                           // to make sure you aren't getting nothing else
    }
    ?>
    

    Also as @Ismail mentioned dataType : 'json' add this in .AJAX call to accept JSON response from API.

    已采纳该答案
    打赏 评论
  • dongxieyou3314 2016-07-27 12:39

    in main_js.js

    function Send(){
        var data_JSON = {
            input: "test",
            message: "Sending..."
        };          
        $.ajax({
            url: 'main_php.php',
            type: 'POST',
            data: data_JSON,
            dataType: 'json',
            success: function(response){                
                if(response.type == "success")               
                {
                     alert(JSON.stringify(response.data));
                     alert(response.data.input);
                     document.getElementById("result").innerHTML =  response.message;          
                }
                else
                {
                     document.getElementById("result").innerHTML = response.message;          
                }
    
            }       
        }); 
    } 
    

    in php code

    <?php
    $response= array();
    if (isset($_POST) && !empty($_POST)){        
        // Make a array with the values
        $vals = $_POST;      
        $response['data']=json_encode($vals);     // Now we want to JSON     
        $response["type"]="success";
        $response["message"]="Successfully posted";
    }
    else
    {
        $response=array(
           "type"=>"error",
           "message"=>"invalid post method"
        );
    }
    ob_clean();
    echo json_encode($response);
    
    打赏 评论

相关推荐 更多相似问题