admin管理员组

文章数量:1391999

When I try to make jQuery AJAX requests in PHP, I have several issues. What's the problem with my simple example?

index.php - loading JS, PHP and defining a button and a paragraph.

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

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

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

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

main.php - it listens to POST requests, and sends back a JSON.

<?php
if ($_POST){        
    // Make a array with the values
    $vals = [
        'input'     => $input,
        'message'   => $message
    ];

    echo json_encode($vals);
}

The success callback runs, but the alert message is entirely empty. alert(data.input) shows undefined.

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

When I try to make jQuery AJAX requests in PHP, I have several issues. What's the problem with my simple example?

index.php - loading JS, PHP and defining a button and a paragraph.

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

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

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

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

main.php - it listens to POST requests, and sends back a JSON.

<?php
if ($_POST){        
    // Make a array with the values
    $vals = [
        'input'     => $input,
        'message'   => $message
    ];

    echo json_encode($vals);
}

The success callback runs, but the alert message is entirely empty. alert(data.input) shows undefined.

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

Share Improve this question edited Oct 12, 2019 at 0:27 Zoltán Schmidt asked Jul 27, 2016 at 12:30 Zoltán SchmidtZoltán Schmidt 1,3452 gold badges30 silver badges50 bronze badges 8
  • I'm sure this can help you out: stackoverflow./questions/8050709/… – Marc Giroux Commented Jul 27, 2016 at 12:32
  • Dont think this is actually your problem, but you are passing data between 2 programs. You dont need the JSON_PRETTY_PRINT – RiggsFolly Commented Jul 27, 2016 at 12:36
  • So have you looked at the contents of data using the browsers javascript debugger – RiggsFolly Commented Jul 27, 2016 at 12:39
  • @RiggsFolly can you explain, how can I do it? – Zoltán Schmidt Commented Jul 27, 2016 at 12:40
  • 1 Its a debugger. Put a breakpoint on the alert() line – RiggsFolly Commented Jul 27, 2016 at 12:44
 |  Show 3 more ments

2 Answers 2

Reset to default 5

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.

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

本文标签: javascriptjQuery AJAX gets no response from PHPStack Overflow