简体   繁体   中英

PHP _POST with Ajax not working

I have the following JavaScript code:

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'></script>
<script>
    function sterge(id_user){
        console.log(id_user);
        var mesaj_post ='id_user=' + id_user;
        $.ajax({
            type: 'post',
            url: 'deleteStudent.php',
            data: mesaj_post,
            dataType: 'text',
            cache: false,
            success:function(data){
                console.log(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError);
            }
        });
    }
</script>

The problem is that in the PHP file called by function, POST is empty and I don't understand why. The parameter of the function is not empty/null, and script result is SUCCESS

PHP Code:

<?php
include 'connect.php';
if(isset($_POST['id_user']))
    echo $_POST['id_user'];
else
    echo "empty post";
?>

Can you help me fix it? Any help would be appreciated.

Thank You!

As @charlietfl first said in his comment, the replace was the problem. But not only that one. The form was also doing a replace.

Thank You!

I pointed out in my comment

Remove the window.location.replace - it calls your php with a GET and no id_user

Had you posted your form too, we could have seen you did not cancel the submission. I hope you did that with something like

$("#formID").on("submit",function(e) { 
  e.preventDefault(); 
  $.post("deleteStudent.php",{ "id_user":$("#id_user").val() }, function(data) { 
    console.log(data); 
  });
});

of course this error occurs, you pass a string not josn object to correct this error you should do the following in javascript code : mesaj_post ={'id_user': id_user}; :)

Try with this code this may do helpful for you

function sterge(id_user){
    console.log(id_user);
    var mesaj_post = {
        "id_user":id_user
    };
    $.ajax({
        type: 'post',
        url: 'deleteStudent.php',
        data: mesaj_post,
        dataType: 'text',
        cache: false,
        success:function(data){
            console.log(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
        }
    });
}

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