How to print an API reponse value in a table column without the values being overidden?

Viewed 26

I am working on a website using django, django-filter ,django-crispy-forms, and datatables for easy pagination and filtering. I have been able to successfully implement the required view and datatable in order to pull data from the django database and print it in a table how I want it presented.

The issue I am running in to, is that I need to fill one of the column items on each row of the table with a value that comes from an API call to a separate website to get the status of an individual player in current time. As you can see from the below snippet, my most recent attempt was using ajax to pull the require api data (Note: I have also tried using fetch, and some javascript). But no matter what I am trying I am unable to get and print the data as required.

In the below using ajax, I run into an issue, where when the for loop runs (2 iterations), if I leave async as true it runs and fills out the first row of the column in question, but does not put data in any other row. When I check the console I can see that the api call actually ran both times in the for loop, but is either only printing once, or is overriding what is printed the first time the second go around. If I set "async: false" in the ajax command when I load the page I see it fill in the first item during the first api call, and then when it fills in the second item on the second api call of the for loop it removes the data from the first row.

What is the best practice or method of doing this, so that I can fill each row of the column with the require response from the api?

(If my naming, syntax, or "best practices" are not correct I apologize, I am sort of learning this on the run since I have minimal experience with many of the scripting languages. ) If any further code snippets are required please advise, I was not sure how much would be needed and did not want to spam too much.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href= "{%  static 'css/style.css' %}">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
 <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <title>TornEQCenter Targets</title>
</head>
<body>
    <nav class="navbar">
        <div class="menubar">
            <ul class="list">
                {% if user.is_authenticated %}
                <li class="list-items"><a href="home">TornEQCenter</a></li>
                <li class="list-items"><a href="targets">Targets</a></li>
                <div class="collapse navbar-collapse" id="navbarText">
                  <ul class="navbar-nav mr-auto">
                   
                    <li class="nav-item">
                      <a class="nav-link" href="logout">Logout</a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="home">Welcome, {{user.username}}</a>
                    </li>
                    {% else %}
                    <li class="nav-item">
                      <a class="nav-link" href="login">Login</a>
                    </li>
              
                    {% endif %}
                    </ul>
                  </div>
                </nav>
            </ul>
        </div>
    </nav>
    <main id="main-holder">
        {% if user.is_authenticated %}
        <H1>Leveling and Chain Targets</H1>
        {% block content %}
        <div class="row">
          <div class="col-md">
          <div class="card card-body">
            <table cellspacing="5" cellpadding="5" border="0" class="centered-table" >
              <thead><tr>
                  <td>Minimum Stats:</td>
                  <td><input type="text" id="min" name="min"></td>
              </tr>
              <tr>
                  <td>Maximum Stats:</td>
                  <td><input type="text" id="max" name="max"></td>
              </tr>
            </thead>
        </table>
          <table id="targetstable" class="styled-table">
          <thead>
              <th>Username</th>
              <th>UserID</th>
              <th>User Status</th>
              <th>TotalStats</th>
              <th>Str</th>
              <th>Def</th>
              <th>Spd</th>
              <th>Dex</th>
          </thead>
          {% for obj in tcp %}
          <tr>
              <td><a href="https://www.torn.com/profiles.php?XID= '{{obj.tcpuserid}}'" target="_blank">{{obj.tcpusername}}</a></td>
              <td>{{obj.tcpuserid}}</td>
              <td>  
                <script>        
                  $(document).ready(function(){
                    $.ajax({
                        url: "https://api.torn.com/user/{{obj.tcpuserid}}?selections=&key=9iUftIRM7DydKZKE",
                        type: "GET",
                        success: function(result){
                            console.log(result);
                            value = result.status.description;
                            $("#tdtargetstatus").html(value);
                        }
                    })
                })
              </script> 
              <div Id="tdtargetstatus"></div>   
              </td>
              <td>{{obj.tcptotalstats}}</td>
              <td>{{obj.tcpstr}}</td>
              <td>{{obj.tcpdef}}</td>
              <td>{{obj.tcpspd}}</td>
              <td>{{obj.tcpdex}}</td>
          </tr>
          {% endfor %}
          </table>     
          </div>
          </div>
        </div>


        <script>
            $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
                var min = parseInt($('#min').val(), 10); //store min needed for range comp
                var max = parseInt($('#max').val(), 10); //store max needed for range comp
                var mxstats = parseFloat(data[2]) || 0;  //store the column in which the data we are performing the range valdiation on it stored, note arrays start with index 0
            
                if (
                    (isNaN(min) && isNaN(max)) ||
                    (isNaN(min) && mxstats <= max) ||
                    (min <= mxstats && isNaN(max)) ||
                    (min <= mxstats && mxstats <= max)
                ) {
                    return true;
                }
                return false;
            });
            
            $(document).ready(function () {
                var table = $('#targetstable').DataTable();
            
                // Event listener to the two range filtering inputs to redraw on input
                $('#min, #max').keyup(function () {
                    table.draw();
                });
            });
        </script>
        {% endblock %}
        {% endif %}
    </main>
</body>
</html>

https://i.stack.imgur.com/numP1.png https://i.stack.imgur.com/k0C24.png

0 Answers
Related