JQUERY/AJAX duplicate JSON results

Asked

Viewed 350 times

2

Gentlemen, I am making a query in a URL that returns me the results of games, but this showing me the duplicate results, could give me a light of where I may be missing?

Here where I consult:

var dadosJson = '';
$(".carregando").show();
$.getJSON("https://api.the-odds-api.com/v3/odds/?sport=upcoming&region=us&mkt=h2h&apiKey=e2d83afb38831daf6779f63a47c32d38#", function(retorno){
$.each(retorno.data, function (i) {
      console.log(retorno.data[i]);

$.each(retorno.data[i].sites, function(a, key){

        $.each(retorno.data[i].teams, function(c, key){

            $.each(retorno.data[i].sites[a], function(b, key){

                primeira = retorno.data[i].sites[a].odds.h2h[0];
                segunda = retorno.data[i].sites[a].odds.h2h[2];
                terecira = retorno.data[i].sites[a].odds.h2h[3];

                esporte = retorno.data[i].sport_nice;
                timeMandante = retorno.data[i].home_team;
                times = retorno.data[i].teams[c];
***********AQUI ONDE MONDO O LAYOUT QUE QUERO QUE SEJA RETORNADO*************
})

            $('.esportes').html(dadosJson);

        });
    })
});
$(".carregando").hide(); 
})

Here is a print of the JSON return in the first $.each.

inserir a descrição da imagem aqui

Thanks in advance!

1 answer

8


I didn’t understand very well, but there are some typos and Indice. is returning the whole object, just need to access the information correctly. believe with these variables that you created can recover all information correctly :)

<!DOCTYPE html>
<html>
<head>
    <title>teste</title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
    var dadosJson = '';
$.getJSON("https://api.the-odds-api.com/v3/odds/?sport=upcoming&region=us&mkt=h2h&apiKey=e2d83afb38831daf6779f63a47c32d38#", function(retorno){
$.each(retorno.data, function (i) {
      console.log(retorno.data[i]);

$.each(retorno.data[i].sites, function(a, key){

        $.each(retorno.data[i].teams, function(c, key){

            $.each(retorno.data[i].sites[a], function(b, key){

                primeira = retorno.data[i].sites[a].odds.h2h[0];
                segunda = retorno.data[i].sites[a].odds.h2h[1];
                terceira = retorno.data[i].sites[a].odds.h2h[2];

                esporte = retorno.data[i].sport_nice;
                timeMandante = retorno.data[i].home_team;
                times = retorno.data[i].teams[c];
// ***********AQUI ONDE MONDO O LAYOUT QUE QUERO QUE SEJA RETORNADO*************
})

            console.log(primeira);
            console.log(segunda);
            console.log(terceira);
            console.log(esporte); //ex bundesliga germany   
            console.log(timeMandante); //time da casa
            console.log(times); //time adversario

            return (dadosJson);

        });
    })
});

})
</script>


</body>
</html>

About adding only 10, it is possible yes, however, to tell the truth you would have to make ajax request, and pass to the file the date you recovered from json, and thus be able to manipulate the server side information, with php. Dai is to make pagination and put the values in the table or somewhere.

So in this case, it would be a real pagination? if it is, I usually do it by manipulating database data, by php and not jquery, but I did it once with jquery... here is more or less an example, adapted from the codetube', to give some idea, I hope it helps:

It is recommended to put active classes to identify which page is currently, put with the real API data, in case ajax is the best solution using the API. Then put as many as you want per page in select or in some other element or leave fixed 10.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>teste</title>
</head>
<body>
    <!-- paginação -->

    <div class="container">
        <h4>Número de Linhas</h4>
        <div class="form-group">
            <select name="state" id="maxRows" class="form-control" style="width:100px;">
                <option value="5">5</option>
                <option value="10">10</option>
                <option value="25" selected="">Tudo</option>
            </select>
        </div>
    </div>

    <div class="form-group">
        <span>obs: valores estáticos</span>
        <table id="table" class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Esporte</th>
                    <th>Casa</th>
                    <th>Visitante</th>
                </tr> 
            </thead>
            <tbody>
                <!-- simulando varios dados com php, porém na web vai pegar apenas1 no exemplo-->
                <!-- <?php for($i=0;$i<25;$i++){ ?> -->
            <!--<tr>
                    <td>Bundesliga 2</td>
                    <td>Darmstadt 98</td>
                    <td>Erzgebirge Aue</td>
                </tr> -->
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                <tr><td>Bundesliga 2</td><td>Darmstadt 98</td><td>Erzgebirge Aue</td>
                </tr>
            <!-- <?php } ?> -->
            </tbody>
        </table>

        <!-- paginação -->
        <div class="paginator-container">
            <nav aria-label="Page navigation example">
                <ul class="pagination">
                    <li style="cursor: pointer;" class="paginacao"><a href="#"></a></li>
                </ul>
            </nav>
        </div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- BOOTSTRAP -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


<!-- paginacao -->
<script>
    var table = '#table';
    $('#maxRows').on('change', function(){
        $('.paginacao').html('')
        var trnum = 0
        var maxRows = parseInt($(this).val())
        var totalRows = $(table+' tbody tr').length
        $(table+' tr:gt(0)').each(function(){  
            trnum++
            if(trnum > maxRows)
                $(this).hide()
            if(trnum <= maxRows)
                $(this).show()
        })

        if(totalRows > maxRows){
            var num_pagina = Math.ceil(totalRows/maxRows)
            for(var i=1;i<num_pagina;){
                $('.paginacao').append('<a data-page="'+i+'">'+ i++ +'<span class="sr-only">(current)</span></a>').show()
            }
        }

        $('.paginacao a').on('click',function(){
            var num_pagina = $(this).attr('data-page')
            var trIndex = 0;
            $(table+' tr:gt(0)').each(function(){
                trIndex++
                if(trIndex > (maxRows*num_pagina) || trIndex <= ((maxRows*num_pagina)-maxRows)){
                    $(this).hide()
                }else{
                    $(this).show()
                }
            })
        })
    })
    $(function(){
        $('table tr:eq(0)').prepend('<th>ID</th>')
        var id = 0;
        $('table tr:gt(0)').each(function(){
            id++
            $(this).prepend('<td>'+id+'</td>')
        })
    })
</script>


</body>
</html>

Hello again. I went to see more in depth about the API so after studying a little more, I realized a few things. It returns only 8 games, those that are happening and those that are to come. but is updated as soon as it ends it returns more.

Now accessing the comments I made there, I put some links. of the games tomorrow, so you can check today. I realized that tomorrow has 5 games, so have (3) games that are the league’s second division. I left the most clear information.

So I think you can recover these games and filter better by separating the divisions and/or adding the other values you need. The good thing is that only 8 dynamic data is better to work on the screen. without requiring paging but appeal to the same front-end. I hope I’ve helped once more :)

Obs: I suggest copying the code to your editor, which in the code extension is without word-wrap making it difficult to read the comments.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>teste</title>
</head>
<body>

<!-- 
    Estudando a API : https://the-odds-api.com/liveapi/guides/v3/#overview
    creio eu que a API só mostre 8 recentes, que estão acontecendo ou que vai acontecer, no caso, os jogos de hoje e os jogos de amanha.

    Nesse exato momento, acabou todos os jogos de hoje; então aparece 8, que são 5 da bundesliga de acordo com liga US;

    //==================
    sport   The sport key obtained from calling the /sports method. upcoming is always valid, returning any live games as well as the next 8 upcoming games across all sports 

    Aqui o site que vi os jogos para conferir
    
    https://www.google.com/search?rlz=1C1NDCM_pt-BRBR787BR787&ei=bXnNXvCVJ6a85OUPmsyXiAw&q=bundesliga&oq=bundesliga&gs_lcp=CgZwc3ktYWIQAzIKCAAQgwEQRhD9ATIFCAAQgwEyBQgAEIMBMgUIABCDATIFCAAQgwEyBQgAEIMBMgUIABCDATIFCAAQgwEyAggAMgUIABCDAToECAAQR1CQ6QNYqPADYILxA2gAcAF4AIABgAGIAfMHkgEDMS44mAEAoAEBqgEHZ3dzLXdpeg&sclient=psy-ab&ved=0ahUKEwiwgOXQrNLpAhUmHrkGHRrmBcEQ4dUDCAw&uact=5#sie=lg;/g/11fk0cxp0k;2;/m/037169;mt;fp;1;;


    Então pro código json:
    //========================
    https://api.the-odds-api.com/v3/odds/?apiKey=e2d83afb38831daf6779f63a47c32d38&sport=upcoming&region=us&mkt=h2h
    
    Pode colocar diretamente no navegor, recomendo o plugin do JSONView para ver organizado os dados. Então aqui apareceu os jogos de amanha 27/05 e mais 3 jogos da bundesliga2 que é a 2º divisão; em geral, no site da bundesliga são no máximo 5 jogos por dia. Então creio eu que vai aparecer os jogos que estão acontecendo, logo depois que acabar um, vai vir outro upcoming de hoje/amanha;

    percebi que a API key free tem limite de requisição, então tem que tomar cuidado se for free a sua. (500 requests per month)

-->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- SCRIPT PRINCIPAL -->
<script type="text/javascript">
    var dadosJson = $.getJSON("https://api.the-odds-api.com/v3/odds/?sport=upcoming&region=us&mkt=h2h&apiKey=e2d83afb38831daf6779f63a47c32d38#", function(retorno){

        $.each(retorno.data, function (i) {
            times = retorno.data[i].teams;
            home_team = retorno.data[i].home_team;
            console.log('|=====Jogo=====|')
            console.log(times);
            console.log('Time da casa: '+home_team);
            console.log('');
        })
    });
</script>
</body>
</html>

  • 2

    That’s right @Joao-pedro-Maciel, thank you very much!

  • 1

    Taking advantage @João Paulo Maciel, I would like to show only 10 results?

  • 1

    Show, that’s what I was wondering! Thank you so much @João-Pedro-Maciel

  • 1

    Good afternoon! @João-Pedro-Maciel, I need to bring only 15 more recent records, which will happen or are happening, I don’t need a pagination and I don’t need to keep the values. Could you help me? Thank you

  • Good morning @João-Pedro-Maciel, that’s right, this API is then limited by the FREE plan, thank you very much for the clear answers!

  • Good morning, I hope I’ve really helped :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.