Implementing TheMovieDB (TMDB) API with jQuery AJAX

Implementing TheMovieDB (TMDB) API with jQuery AJAX

The TheMovieDB (TMDB) API provides all the information of movies, actors and series, free of charge. You can integrate this API in your Website using only jQuery AJAX.

Introduction

In this tutorial I will allow user to search for any actor (like Tom Cruise, Nicole kidman, Tom Hanks, etc). The actor results will be shown in a grid structure created with div elements. On clicking on any actor in this result, the whole information of the actor is shown to the user.

I will create this entire feature in just a HTML page using just jQuery. I will fetch all the actors and their information from the TMDB API with jQuery AJAX.

TMDB API Application Diagram

Generate TheMoviewDB (TMDB) API Key

You can generate TMDB API by first creating your account on the TMDB Website and then go to the Settings area to generate this API.

HTML Page Code
  • The HTML Page is fairly simple, there is a text box and a button. User enters the actor name on the text box and presses the button.
  • There is a loading.gif image that will be shown during AJAX calls. The result of the search is shown inside the message div.
  • I will also show paging links as the API will return the results in thousands. For creating paging links I am using a jQuery Pagination Plugin.
<input type="text" id="searchInput" placeholder="Search actor">
<button id="submit">Submit</button>
<div class="imageDiv">
    <img src="Image/loading.gif">
</div>
<div id="message"></div>
<ul id="pagination"></ul>
The CSS Code

Add the CSS code given below to make the proper design for the HTML page.

#apiDiv {
    border: dashed 2px #CCC;
    padding: 10px;
    padding-left: 20px;
}

    #apiDiv input, #apiDiv button {
        font-size: 25px;
        color: #000;
    }

    #apiDiv h4 {
        margin: 10px 0;
    }

    #apiDiv .imageDiv {
        text-align: center;
    }

        #apiDiv .imageDiv img {
            display: none;
        }

    #apiDiv #message {
        padding-top: 10px;
    }

        #apiDiv #message .resultDiv {
            background: #FFF;
            display: inline-block;
        }

            #apiDiv #message .resultDiv &gt; p {
                color: #000;
                display: inline-block;
                width: 95%;
                padding: 10px;
                border-bottom: double 2px #CCC;
            }

            #apiDiv #message .resultDiv .result {
                width: 23%;
                height: 300px;
                padding: 6px;
                float: left;
                text-align: center;
                cursor: pointer;
            }

                #apiDiv #message .resultDiv .result img {
                    width: 75%;
                }

                #apiDiv #message .resultDiv .result p {
                    margin: 0;
                }

                    #apiDiv #message .resultDiv .result p a {
                        color: #808080;
                        text-decoration: none;
                        font-size: 20px;
                        height: 100px;
                    }

                        #apiDiv #message .resultDiv .result p a:hover {
                            text-decoration: underline;
                        }

#myModal {
    color: #000;
}

#reset {
    padding: 5px 10px;
    background: #4CAF50;
    border: none;
    color: #FFF;
    cursor: pointer;
}

    #reset:hover {
        color: #4CAF50;
        background: #FFF;
    }

jQuery AJAX to call TheMovieDB API

The TMDB API provides the result in JSON format. See the TMD API Docs, you will find that the API request is send to:

https://api.themoviedb.org/3/search/person?api_key=<<api_key>>&language=en-US&query=<<actor_name>>&page=<<page_number>>&include_adult=false

You have to provide the API key, actor name and page number to this URL.

The API response is in JSON whose format is given below:
{
  "page": 1,
  "results": [
    {
      "profile_path": "/2daC5DeXqwkFND0xxutbnSVKN6c.jpg",
      "adult": false,
      "id": 51329,
      "known_for": [
        {
          "poster_path": "/y31QB9kn3XSudA15tV7UWQ9XLuW.jpg",
          "adult": false,
          "overview": "Light years from Earth, 26 years after being abducted, Peter Quill finds himself the prime target of a manhunt after discovering an orb wanted by Ronan the Accuser.",
          "release_date": "2014-07-30",
          "original_title": "Guardians of the Galaxy",
          "genre_ids": [
            28,
            878,
            12
          ],
          "id": 118340,
          "media_type": "movie",
          "original_language": "en",
          "title": "Guardians of the Galaxy",
          "backdrop_path": "/bHarw8xrmQeqf3t8HpuMY7zoK4x.jpg",
          "popularity": 9.267731,
          "vote_count": 5002,
          "video": false,
          "vote_average": 7.97
        },
        {
          "poster_path": "/eshEkiG7NmU4ekA8CtpIdYiYufZ.jpg",
          "adult": false,
          "overview": "When three friends finally come to after a raucous night of bachelor-party revelry, they find a baby in the closet and a tiger in the bathroom. But they can't seem to locate their best friend, Doug -- who's supposed to be tying the knot. Launching a frantic search for Doug, the trio perseveres through a nasty hangover to try to make it to the church on time.",
          "release_date": "2009-06-05",
          "original_title": "The Hangover",
          "genre_ids": [
            35
          ],
          "id": 18785,
          "media_type": "movie",
          "original_language": "en",
          "title": "The Hangover",
          "backdrop_path": "/39LohvXfll5dGCQIV9B9VJ16ImE.jpg",
          "popularity": 3.69347,
          "vote_count": 3761,
          "video": false,
          "vote_average": 7.08
        },
        {
          "poster_path": "/ilrZAV2klTB0FLxLb01bOp5pzD9.jpg",
          "adult": false,
          "overview": "After spending eight months in a mental institution, a former teacher moves back in with his parents and tries to reconcile with his ex-wife.",
          "release_date": "2012-09-08",
          "original_title": "Silver Linings Playbook",
          "genre_ids": [
            18,
            35,
            10749
          ],
          "id": 82693,
          "media_type": "movie",
          "original_language": "en",
          "title": "Silver Linings Playbook",
          "backdrop_path": "/4MKAnhMC32FIXFKSQmKkxLtHHfs.jpg",
          "popularity": 3.277653,
          "vote_count": 3074,
          "video": false,
          "vote_average": 6.9
        }
      ],
      "name": "Bradley Cooper",
      "popularity": 6.431053
    },
    {
      "profile_path": "/4XAtJsz67pmpIsCQ9SBKfqayk2d.jpg",
      "adult": false,
      "id": 154689,
      "known_for": [
        {
          "poster_path": "/xn3QM6aInhQp631K2lXpGFox2Kc.jpg",
          "popularity": 6.605526,
          "id": 60866,
          "overview": "A medical student who becomes a zombie joins a Coroner's Office in order to gain access to the brains she must reluctantly eat so that she can maintain her humanity. But every brain she eats, she also inherits their memories and must now solve their deaths with help from the Medical examiner and a police detective.",
          "backdrop_path": "/d2YDPTQPe3mI2LqBWwb0CchN54f.jpg",
          "vote_average": 6.01,
          "media_type": "tv",
          "first_air_date": "2015-03-17",
          "origin_country": [
            "US"
          ],
          "genre_ids": [
            27,
            18,
            80,
            10765
          ],
          "original_language": "en",
          "vote_count": 69,
          "name": "iZombie",
          "original_name": "iZombie"
        },
        {
          "poster_path": "/uK7Y7ajLx9bmM34COQzQ35HqlSr.jpg",
          "popularity": 7.267267,
          "id": 7225,
          "overview": "Merlin is a British fantasy-adventure television programme by Julian Jones, Jake Michie, Julian Murphy and Johnny Capps. It was broadcast on BBC One from 20 September 2008 to 24 December 2012. The show is loosely based on the Arthurian legends of the young wizard Merlin and his relationship with Arthur Pendragon but differs from traditional versions in many ways. The show was influenced by the US drama series Smallville, about the early years of Superman, and was produced by independent production company Shine Limited.\n\nThe show was greenlit by the BBC in 2006, after unsuccessful attempts. The series premiered in 2008 to mixed reviews but decent ratings, and proved popular on the BBC's digital catch-up service, iPlayer. It was commissioned by the BBC for a second series, and was picked up in the United States by one of the main broadcasters, NBC, though it later moved to the cable network Syfy due to low ratings. In 2012, the show's producers announced that its fifth series would be its last, with a two-part finale finishing the show on 24 December 2012.",
          "backdrop_path": "/c1nR2MRShXYqY04I6V3qwebvkB7.jpg",
          "vote_average": 6.45,
          "media_type": "tv",
          "first_air_date": "2008-09-20",
          "origin_country": [
            "GB"
          ],
          "genre_ids": [
            10759,
            18,
            10751,
            10765
          ],
          "original_language": "en",
          "vote_count": 20,
          "name": "Merlin",
          "original_name": "Merlin"
        },
        {
          "poster_path": "/wa1nzcXxjwKRadtd78tIA9VJqbe.jpg",
          "popularity": 2.109448,
          "id": 19033,
          "overview": "After discovering his origins, Damien Thorn must cope with life as the Anti-Christ.",
          "backdrop_path": "/yBHu4S7ZXlFOSUVT4tRQAuEQx9f.jpg",
          "vote_average": 6.35,
          "media_type": "tv",
          "first_air_date": "2016-03-07",
          "origin_country": [
            "US"
          ],
          "genre_ids": [
            18
          ],
          "original_language": "en",
          "vote_count": 10,
          "name": "Damien",
          "original_name": "Damien"
        }
      ],
      "name": "Bradley James",
      "popularity": 2.67723
    }
],
  "total_results": 363,
  "total_pages": 19
}

So in the HTML page add the jQuery code given below:

<script>
$(document).ready(function () {
    $("#submit").click(function (e) {
        var validate = Validate();
        $("#message").html(validate);
        if (validate.length == 0) {
            CallAPI(1);
        }
    });
    function CallAPI(page) {
        $.ajax({
            url: "https://api.themoviedb.org/3/search/person?language=en-US&query=" + $("#searchInput").val() + "&page=" + page + "&include_adult=false",
            data: { "api_key": "3356865d41894a2fa9bfa84b2b5f59bb" },
            dataType: "json",
            success: function (result, status, xhr) {
                var resultHtml = $("<div class=\"resultDiv\"><p>Names</p>");
                for (i = 0; i < result["results"].length; i++) {

                    var image = result["results"][i]["profile_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w500/" + result["results"][i]["profile_path"];

                    resultHtml.append("<div class=\"result\" resourceId=\"" + result["results"][i]["id"] + "\">" + "<img src=\"" + image + "\" />" + "<p><a>" + result["results"][i]["name"] + "</a></p></div>")
                }

                resultHtml.append("</div>");
                $("#message").html(resultHtml);

                Paging(result["total_pages"]);
            },
            error: function (xhr, status, error) {
                $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    }

    function Validate() {
        var errorMessage = "";
        if ($("#searchInput").val() == "") {
            errorMessage += "► Enter Search Text";
        }
        return errorMessage;
    }

    function Paging(totalPage) {
        var obj = $("#pagination").twbsPagination({
            totalPages: totalPage,
            visiblePages: 5,
            onPageClick: function (event, page) {
                CallAPI(page);
            }
        });
    }
    $(document).ajaxStart(function () {
        $(".imageDiv img").show();
    });

    $(document).ajaxStop(function () {
        $(".imageDiv img").hide();
    });
});
</script>

Explanation
On the button click the CallAPI() method is called. This method makes the jQuery AJAX call to the TMDB API.
It takes the page number as parameter. In this button click event I passed 1 for page number because I want the API should be called to get the results of the first page.

Explanation of jQuery AJAX function

On the jQuery AJAX Success callback function, I am looping through the JSON result and extracting the values from it. These values are put in a div structure which the message div will show.

In the div structure I create custom attribute named resourceId and add the id of every result to it. Later on I will use these ids to make another jQuery AJAX request to fetch the complete information for that id.
  • I make a call to the Paging() function. The work of this function is to create paging links using the jQuery Pagination Plugin.
  • The JSON also provide the total number of pages for the result and this is provided to the Paging() function to create the paging links.

Explanation of Validate() function
This function will force user to enter some text in the text box before clicking the button. This is done because the API needs some actor name for query field.

Testing the Functionality

You can now test the API by entering text Tom in the text box and press the button. The result will look like the image below:

tmdb api first page result for search text tom

Adding Bootstrap Modal Functionality

The API has started giving back the result. I want to add a functionality that on clicking any actor picture will get me the full details of that actor, like his biography, image, birthday, place of birth, etc.

I want to show these details inside a Bootstrap Modal. For this I will have to create a Bootstrap Modal and make another API call (this time for getting the actor full details). This result is shown inside the Modal.

This is how to Proceed

First Add bootstrap.css link on the head section of the HTML page.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Next add the bootstrap.js link on the bottom of the page (just below your jQuery link).

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Then add the bootstrap Modal link on the page (below the pagination div):

<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="modalTitleH4"></h4>
            </div>
            <div class="modal-body" id="modalBodyDiv">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Add the jQuery Function to make the new API request and bind the Modal.

$("#message").on("click", ".result", function () {
    var resourceId = $(this).attr("resourceId");
    $.ajax({
        url: "https://api.themoviedb.org/3/person/" + resourceId + "?language=en-US",
        data: {
            api_key: "3356865d41894a2fa9bfa84b2b5f59bb"
        },
        dataType: 'json',
        success: function (result, status, xhr) {
            $("#modalTitleH4").html(result["name"]);

            var image = result["profile_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w500/" + result["profile_path"];
            var biography = result["biography"] == null ? "No information available" : result["biography"];

            var resultHtml = $("<p class="\&quot;text-center\&quot;"><img src="\&quot;&quot;" +="" image="" "\"=""></p><p>" + biography + "</p>")

            $("#modalBodyDiv").html(resultHtml)

            $("#myModal").modal("show");
        },
        error: function (xhr, status, error) {
            $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        }
    });
});

Explanation
I created click eventm for every actor result, shown on the message div so whenever a user clicks on them, I can make the new TMDB API call to fetch the complete details.

The API docs are given here.

The API JSON response is:
{
  "adult": false,
  "also_known_as": [],
  "biography": "William Bradley \"Brad\" Pitt (born December 18, 1963) is an American actor and film producer. Pitt has received two Academy Award nominations and four Golden Globe Award nominations, winning one. He has been described as one of the world's most attractive men, a label for which he has received substantial media attention. Pitt began his acting career with television guest appearances, including a role on the CBS prime-time soap opera Dallas in 1987. He later gained recognition as the cowboy hitchhiker who seduces Geena Davis's character in the 1991 road movie Thelma &amp; Louise. Pitt's first leading roles in big-budget productions came with A River Runs Through It (1992) and Interview with the Vampire (1994). He was cast opposite Anthony Hopkins in the 1994 drama Legends of the Fall, which earned him his first Golden Globe nomination. In 1995 he gave critically acclaimed performances in the crime thriller Seven and the science fiction film 12 Monkeys, the latter securing him a Golden Globe Award for Best Supporting Actor and an Academy Award nomination.\n\nFour years later, in 1999, Pitt starred in the cult hit Fight Club. He then starred in the major international hit as Rusty Ryan in Ocean's Eleven (2001) and its sequels, Ocean's Twelve (2004) and Ocean's Thirteen (2007). His greatest commercial successes have been Troy (2004) and Mr. &amp; Mrs. Smith (2005).\n\nPitt received his second Academy Award nomination for his title role performance in the 2008 film The Curious Case of Benjamin Button. Following a high-profile relationship with actress Gwyneth Paltrow, Pitt was married to actress Jennifer Aniston for five years. Pitt lives with actress Angelina Jolie in a relationship that has generated wide publicity. He and Jolie have six children—Maddox, Pax, Zahara, Shiloh, Knox, and Vivienne.\n\nSince beginning his relationship with Jolie, he has become increasingly involved in social issues both in the United States and internationally. Pitt owns a production company named Plan B Entertainment, whose productions include the 2007 Academy Award winning Best Picture, The Departed.\n\nDescription above from the Wikipedia article Brad Pitt, licensed under CC-BY-SA, full list of contributors on Wikipedia.",
  "birthday": "1963-12-18",
  "deathday": "",
  "gender": 0,
  "homepage": "",
  "id": 287,
  "imdb_id": "nm0000093",
  "name": "Brad Pitt",
  "place_of_birth": "Shawnee - Oklahoma - USA",
  "popularity": 1.35777,
  "profile_path": "/lZngQUfDpPwlBRebtFo8XFuk9T3.jpg"
}

The code var resourceId = $(this).attr(“resourceId”); will fetch me the value for the custom attribute resourceId i.e. the id of the actor. That allows me to pass this id to the API URL and fetch the complete details.

These details are bind to the bootstrap modal.

Showing the Complete actor details inside the Modal

You can now check the complete details of an actor by clicking its photo. The result is shown in the bootstrap modal.

showing tom cruise details in bootstrap modal

DEMO DOWNLOAD

Conclusion
This completes the implementation of TMDB API with jQuery AJAX. Hope you like it and don’t forget to check my other tutorials too.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.