简体   繁体   English

Ajax 请求不返回响应

[英]Ajax request doesn't return a response

I need a little help for my ajax request.我的 ajax 请求需要一点帮助。 I think i don't get the good value but i have tried more methods, without success.我认为我没有得到很好的价值,但我尝试了更多方法,但没有成功。

数组简单

阵列信息

The purpose is when we click on Info client , another array is displayed with more info.目的是当我们单击Info client时,会显示另一个数组,其中包含更多信息。 But I always have the last id added and not the id's clicked's row.但我总是添加最后一个 id 而不是 id 的点击行。

My HTML:我的 HTML:

 <div>
    <table id="list_client" border=1>
      <tr>
        <td>#</td>
        <td>Nom</td>
      </tr>
      <?php
      require 'config.php';
      $clients = $db->query('SELECT * FROM client');
        
      foreach ($clients as $client) : ?>
      <tr id="<?php echo $client["id_client"]; ?>">
        <td><?php echo $client["id_client"]; ?></td>
        <td><?php echo $client["nom_client"]; ?></td>
        <td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client']; ?>);">Info client</button></td>
        <td><button type="button" onclick="hide_info(<?php echo $client['id_client']; ?>);">Masquer client</button></td>
      <?php endforeach; ?>
    </table>
  </div>

My JavaScript and Ajax request:我的 JavaScript 和 Ajax 请求:

function display_info() {
    $("#info").click(function () {
        var datas = {
            action: "read",
            id_client: $("#id_client").val(),
        };
        $.ajax({
            type: "GET",
            url: "function.php",
            async: true,
            data: datas,
            dataType: "json",
            cache: false,
        }).done(function (result) {
            console.log("result");
            $("#result").text("response : " + JSON.stringify($result));
        });
    });
}

#result is a div besides the array. #result是数组之外的一个 div。 (to test) (去测试)

My PHP function:我的 PHP function:

function read() {
    global $db;

    $id_client = $_GET['id_client'];

    $client = "SELECT * FROM client WHERE id_client = '$id_client'";
    $query = $db->prepare($client);
    $query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
    $query->execute();
    $result = $query->fetch();
    echo json_encode($result);
}

I think I am close but no idea what I did wrong.我想我很接近,但不知道我做错了什么。

Issues:问题:

  • #1 <tr id="<?php echo $client["id_client"];?>"> #1 <tr id="<?php echo $client["id_client"];?>">

In the above code, how will you dynamically get the id of the client when trying to use it in Javascript?在上面的代码中,在 Javascript 中尝试使用时如何动态获取客户端的 id?

  • #2 <td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client'];?>);">Info client</button></td> #2 <td><button name="info" id="info" type="button" onclick="display_info(<?php echo $client['id_client'];?>);">Info client</button></td>

Above code will make all buttons have same id which is info .上面的代码将使所有按钮具有相同的 id,即info id needs to unique per HTML element. id需要每个 HTML 元素唯一。

  • #3 id_client: $("#id_client").val(), . #3 id_client: $("#id_client").val(), .

There is no element with id as id_client .没有idid_client的元素。

  • #4 function display_info() { $("#info").click(function () { . #4 function display_info() { $("#info").click(function () { .

You are attaching an onclick as well as a click event listener which is not required.您正在附加一个 onclick 以及一个不需要的单击事件侦听器。 Do either of them and not both but I would recommend the latter one.做其中一个而不是两个,但我会推荐后一个。

  • #5 $client = "SELECT * FROM client WHERE id_client = '$id_client'"; #5 $client = "SELECT * FROM client WHERE id_client = '$id_client'";

You aren't preparing the query here with a placeholder but rather just adding the retrieved id in the query which is very unsafe since we can't trust user input.您没有在这里使用占位符准备查询,而只是在查询中添加检索到的 id,这是非常不安全的,因为我们不能信任用户输入。

  • #6 You also missed a closing tr tag. #6你还错过了一个结束的tr标签。

Solution:解决方案:

  • For issue #1 , no need to attach an id attribute to a tr tag at all.对于问题#1 ,根本不需要将id属性附加到tr标签。

  • For issue #2 , make info a class name instead of the id and remove onclick as it isn't needed.对于问题#2 ,将info class名称而不是id并删除onclick因为它不需要。

  • For issue #3 , we would get the id_client value from the data-id attribute which we will attach to the respective info button.对于问题#3 ,我们将从附加到相应info按钮的data-id属性中获取id_client值。

  • For issue #4 , encapsulating click event listener inside display_info is not needed.对于问题#4 ,不需要在display_info中封装 click 事件侦听器。 We can directly attach the listener.我们可以直接附加监听器。

  • For issue #5 , we will add a placeholder for id_client to properly bind our primitive value inside the query.对于问题#5 ,我们将为id_client添加一个占位符,以便在查询中正确绑定我们的原始值。

  • For issue #6 , we will add a closing tr tag.对于问题#6 ,我们将添加一个结束tr标签。 Snippets:片段:

Frontend:前端:

<div>
    <table id="list_client" border=1>
           <tr>
                  <td>#</td>
                  <td>Nom</td>
           </tr>
    <?php
          require 'config.php';
          $clients = $db->query('SELECT * FROM client');
            
          foreach ($clients as $client): 
    ?>
           <tr>
                  <td><?php echo $client["id_client"]; ?></td>
                  <td><?php echo $client["nom_client"]; ?></td>
                  <td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
                  <td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
           </tr>
    <?php endforeach; ?>
    </table>
</div>

<script>
$(".info").click(function(){
    var datas = {
           action: "read",
           id_client: $(this).attr('data-id'),
    };
    $.ajax({
           type: "GET",
           url: "function.php",
           data: datas,
           dataType: "json",
           cache: false,
    }).done(function(result) {
           console.log("result");
           $("#result").text("response : " + JSON.stringify($result));
    });
});

$('.hide_client').click(function(){
       let client_id = $(this).attr('data-id');
       // do your thing here
});
</script>

Backend:后端:

<?php

function read() {
    global $db;
    $id_client = $_GET['id_client'];
    $query = $db->prepare("SELECT * FROM client WHERE id_client = :id_client");
    $query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
    $query->execute();
    $result = $query->fetch();
    echo json_encode($result);
}

Not sure if that's the error you're having, but不确定这是否是您遇到的错误,但是

$client = "SELECT * FROM client WHERE id_client = '$id_client'";

should probably read应该读

$client = "SELECT * FROM client WHERE id_client = :id_client";

as the binding of the prepared statement doesn't work otherwise.因为准备好的语句的绑定在其他情况下不起作用。

Other than that: Can you check which results you get from your select query and if that's the result you expect?除此之外:您能否检查一下您从 select 查询中获得了哪些结果,这是否是您期望的结果?

you are giving the clientid over to the function display_info, you don't need to read it out with jquery... just change您正在将 clientid 交给 function display_info,您无需使用 jquery 将其读出...只需更改

function display_info() {

to

function display_info(clientid) {

and change the并改变

var datas = {
    action: "read",
     id_client: $("#id_client").val(),
   };

to

    var datas = {
    action: "read",
     id_client: clientid,
   };

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

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