不知道如何通过js单击执行php函数

时间:2019-02-14 16:24:12

标签: javascript php ajax

这是我的PHP函数

$sql = "SELECT * FROM `users` WHERE `id` = '".$_SESSION['id']."'";
$result = mysql_query($sql, $db_connection);
$row = mysql_fetch_assoc($result);
$sql = mysql_query("INSERT INTO medrecherche VALUES('','$medname','{$_SESSION['id']}')");

我需要它在我正在开发的搜索弓中单击结果的同时执行,

我的js函数是下面的一个:

function set_item(item) {
    // change input value
    $('#medicine_id').val(item);
    // hide proposition list
    $('#listmed').hide();
}

在index.php中这样称呼

<div class="input_container">
    <input type="text" id="medicine_id" onkeyup="autocomplet()" >                 
    <ul id="listmed"></ul>
</div>

1 个答案:

答案 0 :(得分:-1)

嗨,您可以这样操作:

$("#yourbuttonId").on('click',function(){

var medicineId = $("#medicine_id").val();
///you should validate medicine id here and then call your ajax
$.ajax({
        method: "POST",
        url: "myfile.php",
        data: { action: "INS", medicineId: medicineId }
                            })
                            .done(function( response ) {
                              //response from your php
                                console.log(response);
                            });

})

您的php文件:

   //do your search on a different ajax i guess
    if(isset($_POST["action"]) && $_POST["action"] == "SLC"){
    $sql = "SELECT * FROM `users` WHERE `id` = '".$_SESSION['id']."'";
    $result = mysql_query($sql, $db_connection);
    $row = mysql_fetch_assoc($result);
    echo json_encode($row,JSON_UNESCAPED_UNICODE);
    }
    if(isset($_POST["action"]) && $_POST["action"]== "INS" && isset($_POST["medicineId"])){
      $medname = $_POST[medicineId];
      //validate your medname i guess in this section then do your insert
    $sql = mysql_query("INSERT INTO medrecherche 
     VALUES('','$medname','{$_SESSION['id']}')");
    //and return a response if the insert was sucefull 
     echo "insert-ok"; 

}