通过ajax将php函数传递给javascript

时间:2017-08-09 02:41:34

标签: javascript php ajax

我正在尝试创建一个页面,在搜索时会从我的数据库中删除用户,请求确认,然后删除它,我非常接近,但我需要通过ajax将函数传递给java脚本但是我不明白该怎么做。这是我的代码:

<html> 
<head> 

<?php
    require_once('conn.php');
    function deleteEmployee($conn, $employee, $table){
        $query = "DELETE from $table where EmployeeName = '$employee'";
        $confirmed = mysqli_query($conn, $query);
        if ($confirmed){
            echo "User Deleted";
        }
        else{      
            return True;
            echo 'User has been deleted';
        }
        return;
    }
    //$query1 = 'select *
?>

<script>
    function myFunction() {
        var txt;
        return confirm('Are you sure?');
        if (confirm == true) {
            deleteEmployee($conn, $name, "employee");//This is where i am having trouble
        } else {
             txt = "Okay";
        }
        document.getElementById("demo").innerHTML = txt;
    } 
</script>
</head>
<body>
<p id="demo"></p>
<form action="" method="post">  
    Search Name to be Deleted: <input type="text" name="term" /><br />  
    <button onclick="myFunction()" type="submit" value="Submit" />submit</button> 
</form>  

<?php
if (!empty($_POST['term'])) {

    $term = mysqli_real_escape_string($conn,$_POST['term']);     

    $sql = "SELECT EmployeeName FROM employee "; 
    $r_query = mysqli_query($conn,$sql); 
    if($r_query->num_rows == 0){
         echo "Name not in database";
    } else{
        while ($row = mysqli_fetch_array($r_query)){ 
            $name = $row['EmployeeName'];  
        } 
    }
}
?>

</form> 

     截止到目前为止,窗口弹出,但是当我按下确定时,没有任何反应,因为我不明白如何通过ajax将函数传递给javascript。有人可以帮忙吗?如果您需要更多信息,请告诉我

1 个答案:

答案 0 :(得分:0)

如何使用jQuery AJAX,将php函数存储在不同的文件中,只过去发布/获取数据,以便PHP方法可以处理您想要处理的内容?

示例用法:

$.ajax({
    method: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" }
}).done(function( msg ) {
    alert( "Data Saved: " + msg );
});