简体   繁体   English

PHP _POST与Ajax不起作用

[英]PHP _POST with Ajax not working

I have the following JavaScript code: 我有以下JavaScript代码:

<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. 问题是在函数调用的PHP文件中,POST为空,我不明白为什么。 The parameter of the function is not empty/null, and script result is SUCCESS 该函数的参数不为空/空,脚本结果为SUCCESS

PHP Code: PHP代码:

<?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. 正如@charlietfl在其评论中首先说的那样,替换是问题所在。 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 删除window.location.replace-它使用GET和没有id_user调用您的php

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}; 当然会发生此错误,您可以传递一个字符串而不是josn对象来更正此错误,您应该在javascript代码中执行以下操作: 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);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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