Search code examples
jqueryajaxpage-refresh

update the page data using ajax


If i clicked on books link he will sort the book in ascending and if i clicked again he sort them in descending , but he didn't do this action unless i clicked on next or prev submit, why he didn't update the page with out clicked on next or prev ?

$(document).ready(function() {
$("#sorter").click(function(e) {
e.preventDefault();
var order_by_value = $('input[name="order_by"]').val();
    $.ajax({
      type: 'GET',
       url: "" + 'http://test.local/UUser.php?action=getBooks',
      data:{
     'order_by_value': order_by_value,

     // button: 'button',
      },
      success: function (res) {
        console.log(res);
        if(order_by_value == "ASC"){
       $('input[name="order_by"]').val("DESC");
      }
      else {
       $('input[name="order_by"]').val("ASC");
       }
     // $('input[name="current"]').trigger('click');
    }
   });
});
});

and this is my function

public function getBooks($start = 0, $limit = 2, $order = "ASC")
 {
   $sql_start = $start * $limit;
   $sql_limit = $limit;
   $sql_order_by = $order;

   $query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username ORDER BY Library.nameOfBook $sql_order_by LIMIT $sql_start, $sql_limit";
   $statment = $this->db->prepare($query);
   $statment->execute([
       ':username' => $this->username
   ]);
   $result = $statment->fetchAll();

  echo "<table id='myTable' border='1'>

  <tr>
   <th><a id='sorter' href='#'>Books</a></th>
   <th>Action</th>
   </tr>";
   foreach($result as $row){
       echo "<tr>";
       echo "<td>" . $row['nameOfBook'] . "</td>";
       echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
       echo "</tr>";
   }

   echo "</table>";
   echo "";
   return count($result);

 }

Solution

  • this event is listening on an element with Id sorter, so it's working properly, you just need to display the answer from the server to the client

    success: function (res) {
            console.log(res);
            if(order_by_value == "ASC"){
           $('input[name="order_by"]').val("DESC");
          }
          else {
           $('input[name="order_by"]').val("ASC");
           }
         // $('input[name="current"]').trigger('click');
         //here you display the result from the server
        $("#myTable").html(res);
        }