简体   繁体   中英

PHP file does not receive data from AJAX post

jQuery code:

$(document).ready(function(){
    $('.tablePend tbody').on('click','.btn',function(){
        // var id=$('#test-pend').val();
        var currow=$(this).closest("tr");
        var colId = currow.find('td:eq(3)').text();
        var id = colId;
        alert(id);
        $.post("../admin/detail.php", {
            pid:id
        });
    });
});

So the code above works perfectly, the alert shows the result that I want

<?php
include('dbh.inc.php');
include_once('header.php');

if(isset($_POST['pid'])) {
    $id = mysqli_real_escape_string($conn, $_POST['pid']);
    $sql= "SELECT event_name, event_desc, event_date, event_id FROM events WHERE event_id='$id'";
    $result= mysqli_query($conn, $sql);
    echo $id;
} else {
    echo 'nothing';
}

include_once 'footer.php';
?>

So right here, the PHP automatically goes to the else statement which shows nothing, I don't know what went wrong, I've tried all possible ways, for days, this is really making me frustrated, and I also believe that I made a simple mistake but I can't find it.

In my opinion, you should check $conn. You don't declare it yet in detail.php file.

I had to do some sleuthing to come up with this answer.

Your $.post() jQuery code does not include a success (or error) handler. That means no matter what happens, you won't see the results of what your PHP file says. But in your question, you say you can see nothing . So, this makes me suspect that you are not actually submitting via AJAX at all.

You have shown us jQuery code where you have an event handler attached to your button. My guess is your button is inside aa <form> . When you click a button in a form, it will submit it. If you want your jQuery to handle it instead, you have to explicitly specify that the normal form submission should not happen. And your your jQuery code does not do that.

So what all this means is that when you click the button, the form is submitted normally . Your event handler maybe fires, and that code starts, but meanwhile the browser has moved on to your <form> target, and the jQuery never gets far. Your <form> does not actually include an id , you set that dynamically with jQuery. So you wind up on the <form> target, with no id POSTed, and you see nothing on the page.

The fix is to stop the normal form submission:

$(document).ready(function(){
    $('.tablePend tbody').on('click','.btn',function(event){
        event.preventDefault();
        // rest of your code

Note I have added event as a parameter passed to the event handler, and then used its preventDefault() method. There is an example of this shown in the .post() documentation .

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