How to build an application that lists sports data with jQuery - 2

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@gotgame·
0.000 HBD
How to build an application that lists sports data with jQuery - 2
#### Repository
https://github.com/jquery/jquery

#### What Will I Learn?
By the end of this tutorial the user will know how to build an application that displays sports data for different sports and sport teams.

#### Requirements
In order to be able to follow this tutorial the user has to be able to use the following

- HTML/CSS/MaterializeCSS
- JavaScript/JQuery
- TheSportsDB public api
- AxiosJS

#### Difficulty

Intermediate

#### Tutorial Contents
In this post we are going to cover the following aspects of our application

- List all teams in a league
- List all leagues by sport
- List all leagues in a country

##### List all teams in a league

In this section we will be implementing a feature that allows us to list all the teams present in any league from any sport.

In order to list all the team we will be using a materialize collapsible component which we already implemented in the previous tutorial. 

We want to make it so that whenever a user clicks on a league in in the list of teams in `index.html` a collapsible dropdown will appear showing a list of all the teams in that league.

In `index.html`, we need to add a new `<script></script>` tag after the last `<script></script>` tag in the file and the add the following code inside the tag.

```
function viewTeams() {
            $('.league-name').click(function() {
                const firstElPosition = $(this).text();

                console.log(firstElPosition);
            });
        }
```

Save the file and reload the page.

After reloading the page, if you click on one of the leagues on the list and view the browser console you should see data like this

![sports-data-8.PNG](https://ipfs.busy.org/ipfs/QmRCSPhP8aBLYmXW3snQSKEeevBPQnau7DGgWNhU9VM5Nh)

We need to send a request that will retrieve all teams for the league we chose and display it in the collapsible dropdown.

To do that, replace the line `console.log(firstElPosition);` with the following code

```
const elText = firstElPosition.replace(/ /g, '%20');

                axios.get(`https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=${elText}`).then(response => {
                    console.log(response.data);
                }).catch(err => {
                    console.log(err)
                })
```

![sports-data-9.PNG](https://ipfs.busy.org/ipfs/QmYWHwni4oHbAZemLpBsXPAwxwK4moayYASBXDRCvUtJTs)

To display this data, replace the line `<span>Lorem ipsum dolor sit amet.</span>` in `sports-data.js` with the following

```
<ul class="collection team-collection"></ul>
```

In `index.html`, replace the line `console.log(response.data);` with the following code

```
 const responseArray = response.data.teams;

                    let allTeams = ``;

                    responseArray.forEach(team => {
                        const teamName = team.strTeam;

                        const tableRow = `<li class="collection-item">${teamName}</li>`

                        allTeams = allTeams + tableRow;
                    })
                    $('.team-collection').html(allTeams)

```
Save both files and reload the page, you should get identical results to the images below

![sports-data-10.PNG](https://ipfs.busy.org/ipfs/QmPL8ZFyp6XrQHrHn42285xGkDBV2MrJCHcmaDxtxVuxWe)

![sports-data-11.PNG](https://ipfs.busy.org/ipfs/QmdAXHiAMXYLctMTtcZLmD73JpJpGu7KS52u5dt4sYbs1j)


##### List all leagues by sport

In this section we will add a feature that will display all the leagues/competition present under a particular sport.

In the first tutorial in this series, we implemented a sidenav which contains a list of all sports in the database.

In this tutorial, we will make it so that whenever a user clicks on any sport on the list the view navigates to a list of all leagues existing under that sport.

Remember that when a user clicks on the link `All Sports` at the topmost part of the page the sidenav pops out like in the image below

![sports-data-4.PNG](https://ipfs.busy.org/ipfs/QmQQAPBz5fMfUYDFGSyz6J9uBPSNqeaP2XUCdqpYmriKSN)

To implement our planned feature, we need to visit `sports-data.js`.

In the file, replace the linw `<li class="collection-item">${sportName}</li>` with `<li class="collection-item all-sports-collection" onclick="viewSports()">${sportName}</li>`


In `index.html`, add a new function `viewSports() {}` in the `<script></script> tag we created earlier. 

In the newly function, add the following code.

```
$('.all-sports-collection').click(function() {
                const sportName = $(this).text();
                console.log(sportName);
            })
```

If you save and reload the file, open the sidenav and click in one of the list items you should get something like this in your console

![sports-data-12.PNG](https://ipfs.busy.org/ipfs/QmRKpPSxdqhvRYuMgAJuGwkmvwE5g4WMz7VGhmxC9DcS3L)

In order to get all the leagues under that particular sport, we need to send a request to the api.

Replace the line `console.log(sportName);` in `index.html` with the following code

```
const sportNameSlug =  sportName.replace(/ /g, '%20');

                axios.get(`https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?s=${sportNameSlug}`).then(response => {
                    console.log(response);
                }).catch(err => {
                    console.log(err)
                });
```

Reload the page, open the sidenav and click on a list item to get this type of data in your console

![sports-data-13.PNG](https://ipfs.busy.org/ipfs/QmX1SbDyaszevNxsqKeHrz4PaCNxRbNbEjLayKxbqAzLKR)

In order to display the data on the page, replace `console.log(response);` in `index.html` with the following code

```
const responseArray = response.data.countrys;

                    let sportLeagues = ``;

                    responseArray.forEach(league => {
                        const leagueName = league.strLeague;

                        const tableRow = `<li>
                        <div class="collapsible-header league-name" onclick="viewTeams()">${leagueName}</div>
                        <div class="collapsible-body"><ul class="collection team-collection"></ul></div>
                        </li>`

                        sportLeagues = sportLeagues + tableRow
                    })

                    document.getElementById('leaguesTable').innerHTML = sportLeagues;
```

In `sports-data.js` replace the line `<li class="collection-item all-sports-collection" onclick="viewSports()">${sportName}</li>` with the following code 

```
<li class="collection-item all-sports-collection sidenav-close" onclick="viewSports()">${sportName}</li>
```

Save both files and check the page to see if the implementation is working correctly, if it is then you should an interface like the one in the images below.

![sports-data-14.PNG](https://ipfs.busy.org/ipfs/QmaYENZoA7dGWVjZJKTNHPwQptu7yxoZShPPcvJbmAQ6Eu)

![sports-data-15.PNG](https://ipfs.busy.org/ipfs/QmavyFK8AD26noW5uawq3rHtmUPwTmD5KKZni9Jq5TWToy)

##### List all leagues in a country

Finally, we are going to implement a feature that searches through the api database and returns a list of all leagues in a particular country.

In this section we will add a search form that will take the country name and search through the api database in order to return a list of all leagues in that country.

Upon page load the form will be hidden from view until an event calls for it to be displayed.

The first thing we'll do to go to `index.html` file in order to add the text input for our search form.

In `index.html`, add the following code after the line `<a href="#" data-target="slide-out" class="sidenav-trigger white-text link-text"><b>All Sports</b></a>`

```
<a href="#" onclick="searchCountry()">Search Country</a>
```

In the last `<script></script> tag in the same file add the following code below the last function.

```
function searchCountry() {
            console.log('Search')
        }
```

If you save the file and reload the page you should see a link `Search Country` beside `All Sports` at the topmost part of the page

![sports-data-16.PNG](https://ipfs.busy.org/ipfs/QmcxyjwvMD8yFYxioYm6v4xfVhn2PTM2Dbyd879Tx3xb1z)

When you click on search country and view the browser console you should see a log like the one in the image.

![sports-data-17.PNG](https://ipfs.busy.org/ipfs/QmeXrspDHrV2Vf12kzkVDWB3LHYbohpDP6LLinaJa11vqu)

In `index.html`, add the following code below the line `<a href="#" onclick="searchCountry()">Search Country</a>`

```
<div class="row container center center-align country_search_form_area">
  <div class="col l9 m9 center center-align">
     <input placeholder="Enter Country Name Here" id="country_name" type="text" class="center center-align black-text country_search_form white">
  </div>
  <div class="col l3 m3 center center-align">
     <span><a href="#" class="btn white black-text">search</a></span>
  </div>
</div>
```

We just created the search form itself,as shown in the image below. 

![sports-data-18.PNG](https://ipfs.busy.org/ipfs/QmT2V5WrcA34trSJPDW7vG1W5UksUEt2T8UxfQyzg7arbb)

Now, when the page loads we need the search form to be hidden from view until an event calls for it. To implement that, we'll go to `sports-data.js` and we'll add the following code after the line `$('.collapsible').collapsible();`

```
$('.country_search_form_area').hide();
```

 Save the file and reload the page, you'll find that the form has been hidden from view, in order to display the form again we'll go back to the function `searchCountry()` that we created in `index.html`.

In `searchCountry()`, replace the line `console.log('Search')`, with the following code

```
$('.country_search_form_area').show();
```

Save the file, reload the page and click on `Search Country` then the form will be displayed.

![Webp.net-gifmaker (25).gif](https://ipfs.busy.org/ipfs/QmWYavMgT3x9LP8hTB6dFgmWcxDcoyq35aoJThDmyX6vGJ)

What we want do now is grabbing of data from the form and sending it as part of the request to the api. 

When a user enters a country  name to the text input and clicks the `search` button we need to have a  function that gets the data.

In `index.html`, below the last function we created i.e `searchCountry()`, add the following code for form data grabbing

```
function searchForCountry() {
            const searchData = $('.country_search_form').val();
            console.log(searchData)
        }
```

Save the file, reload the page, if you open the form and type some text, click the search button and you should be able to see the text you typed in the console

![sports-data-19.PNG](https://ipfs.busy.org/ipfs/QmT4GtrJVFXDsbEh1eUDSocmW9qRSSy4RiakZwZZ8ZKV9G)

In order to send the data to to api we need to write a request.

In `index.html`, replace `console.log(searchData)` with the following code 

```
axios.get(`https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${searchData}`).then(response => {
                console.log(response.data);
            }).catch(err => {
                console.log(err);
            });
```

If you enter some text after saving the file and reloading the page you should get data like this in the browser console.

![sports-data-20.PNG](https://ipfs.busy.org/ipfs/QmY4gaiLXhiCKNXt9a2a3RpdwTLyVWfc9jLrsiX4wtAP7R)

To display the data on the page, replace `console.log(response.data);` with the following code.

```
const responseArray = response.data.countrys;

                let countryLeagues = ``;

                responseArray.forEach(league => {
                    const leagueName = league.strLeague;

                    const leagueSport = league.strSport;

                    const tableRow = `<li>
                        <div class="collapsible-header league-name" onclick="viewTeams()">${leagueName}(${leagueSport})</div>
                        <div class="collapsible-body"><ul class="collection team-collection"></ul></div>
                        </li>`

                        countryLeagues = countryLeagues + tableRow
                })
                document.getElementById('leaguesTable').innerHTML = countryLeagues;
              
              $('.country_search_form_area').hide();
```

If you reload the page and run a search through the form you should get a result like the one below.

![Webp.net-gifmaker (26).gif](https://ipfs.busy.org/ipfs/QmeN5S823LzE2PkFfNEXjdHQfEzdjJDmz5w5t2bBGCt3Z1)


#### Curriculum

- https://steemit.com/utopian-io/@gotgame/how-to-build-an-application-that-lists-sports-data-with-jquery-1

#### Proof of work done

https://github.com/olatundeee/sports-data-app
👍 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,