Home > Software design >  Ajax request doesn't return a response
Ajax request doesn't return a response

Time:07-25

I need a little help for my ajax request. I think i don't get the good value but i have tried more methods, without success.

array simple

array info

The purpose is when we click on Info client, another array is displayed with more info. But I always have the last id added and not the id's clicked's row.

My 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:

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. (to test)

My 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.

CodePudding user response:

Issues:

  • #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?

  • #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 needs to unique per HTML element.

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

There is no element with id as id_client.

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

You are attaching an onclick as well as a click event listener which is not required. Do either of them and not both but I would recommend the latter one.

  • #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.

  • #6 You also missed a closing tr tag.

Solution:

  • For issue #1, no need to attach an id attribute to a tr tag at all.

  • For issue #2, make info a class name instead of the id and remove onclick as it isn't needed.

  • For issue #3, we would get the id_client value from the data-id attribute which we will attach to the respective info button.

  • For issue #4, encapsulating click event listener inside display_info is not needed. 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.

  • For issue #6, we will add a closing tr tag. 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" >Info client</button></td>
                  <td><button type="button"  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);
}

CodePudding user response:

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?

CodePudding user response:

you are giving the clientid over to the function display_info, you don't need to read it out with jquery... just change

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,
   };
  • Related