How to Implement IMBD API using jQuery AJAX

How to Implement IMBD API using jQuery AJAX

By implementing IMDB API in a website you can show the visitors all movies, actors and series information, right in our website. Here I will implement the IMDB API using jQuery AJAX method.

The first thing is to create your free IMDB API key from here.

The IMDB API Application

The application is quite simple. Firstly, create an HTML page and add a text box and a button. A user enters his search text into this text box and clicks the button. On the button click, the API call is made and the result is fetched and shown to the user.

IMDB API Application Diagram

The HTML Page Code:

<input type="text" id="searchInput" placeholder="Search IMDB" />
<button id="submit">Submit</button>
<div class="textAlignCenter">
    <img src="loading.gif" />
</div>
<div id="message">
</div>

I have used the “message” div in the HTML page for showing the result returned by the IMDB API.

The “loading.gif” will be shown during AJAX calls. This will tell the user that the AJAX request is under process.

Add the CSS to make the design look good and understandable:

<style>
    body {
        background-color: #000;
    }

    #apiDiv {
        padding-left: 20px;
    }

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

        #apiDiv h4 {
            margin: 10px 0;
        }

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

            #apiDiv .textAlignCenter img {
                display: none;
                width: 100px;
            }

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

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

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

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

                    #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;
    }
</style>

Calling API with jQuery AJAX

Our HTML page is now set so moving towards the button click where I will use the jQuery AJAX to make the API call.

Give the reference to jQuery in the HTML page, before the ending body tag.

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

Create the button click event and inside it add the jQuery AJAX code that will make the API call:

<script>
    $(document).ready(function () {
        $("#submit").click(function (e) {
            var validate = Validate();
            $("#message").html(validate);
            if (validate.length == 0) {
                $.ajax({
                    url: "http://imdb.wemakesites.net/api/search?q=" + $("#searchInput").val(),
                    data: { "api_key": "9c4d2620-32a1-4f4a-abd0-c88b008f383e" },
                    crossDomain: true,
                    dataType: "jsonp",
                    success: function (result, status, xhr) {
                        var resultHtml = $("<div class=\"resultDiv\"><p>Names</p>");
                        for (i = 0; i < result["data"]["results"]["names"].length; i++) {
                            resultHtml.append("<div class=\"result\" resourceId=\"" + result["data"]["results"]["names"][i]["id"] + "\">" + "<img src=\"" + result["data"]["results"]["names"][i]["thumbnail"] + "\" />" + "<p><a>" + result["data"]["results"]["names"][i]["title"] + "</a></p></div>")
                        }

                        resultHtml.append("<p>Titles</p>");
                        for (i = 0; i < result["data"]["results"]["titles"].length; i++) {
                            resultHtml.append("<div class=\"result\" resourceId=\"" + result["data"]["results"]["titles"][i]["id"] + "\">" + "<img src=\"" + result["data"]["results"]["titles"][i]["thumbnail"] + "\" />" + "<p><a>" + result["data"]["results"]["titles"][i]["title"] + "</a></p></div>")
                        }

                        resultHtml.append("</div>");

                        $("#message").html(resultHtml);
                    },
                    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;
        }

        $(document).ajaxStart(function () {
            $(".textAlignCenter img").show();
        });

        $(document).ajaxStop(function () {
            $(".textAlignCenter img").hide();
        });

    });
</script>
Code Explanation

On the button click event I am calling the “Validate()” function. The work of this function is to prevent users from submitting empty text box entries.

The .ajaxStart() and .ajaxStop() are the jQuery AJAX Events that are attached to the document. They are called during the life-time of an AJAX request. I am using them to show and hide the loading image so that people can know when an AJAX request is happening and when it has finished.

Next I am making the API call using jQuery AJAX. I am passing the “url” as “http://imdb.wemakesites.net/api/search?q=” + $(“#searchInput”).val()” which means the value of the textbox is going into the query string variable “q”.

The API key should be passed to the “data” key of the jQuery AJAX method like “data: { “api_key”: “API KEY” },”

The IMDB API sends back the result which I get in the success function. The result is in the form of JSON.

The format of the JSON response is:
{
	"status": "success",
	"code": 200,
	"message": "ok",
	"term": "nicole",
	"search_url": "http://www.imdb.com/find?q=nicole&s=all5899a4b6ce498",
	"data": {
		"results": {
			"names": [
				{
					"title": "Nicole 'Snooki' Polizzi",
					"id": "nm3725472",
					"url": "http://www.imdb.com/name/nm3725472/?ref_=fn_al_nm_1",
					"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/[email protected]_V1_UY44_CR0,0,32,44_AL_.jpg"
				},
				{
					"title": "Nicole Arianna Fox",
					"id": "nm2747803",
					"url": "http://www.imdb.com/name/nm2747803/?ref_=fn_al_nm_2",
					"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/[email protected]@._V1_UY44_CR13,0,32,44_AL_.jpg"
				}
				
			],
			"titles": [
				{
					"title": "Untitled Santa Claus Project",
					"id": "tt6418472",
					"url": "http://www.imdb.com/title/tt6418472/?ref_=fn_al_tt_1",
					"thumbnail": "http://ia.media-imdb.com/images/G/01/imdb/images/nopicture/32x44/film-3119741174._CB522736599_.png"
				},
				{
					"title": "Nicole",
					"id": "tt0077987",
					"url": "http://www.imdb.com/title/tt0077987/?ref_=fn_al_tt_2",
					"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/[email protected]@._V1_UY44_CR0,0,32,44_AL_.jpg"
				}
				
			],
			"characters": [
				{
					"title": "Nicole",
					"id": "ch0262053",
					"url": "http://www.imdb.com/character/ch0262053/?ref_=fn_al_ch_1",
					"thumbnail": ""
				},
				{
					"title": "Nicole",
					"id": "ch0024295",
					"url": "http://www.imdb.com/character/ch0024295/?ref_=fn_al_ch_2",
					"thumbnail": ""
				}

			]
		}
	}
}

From this JSON I am extracting ids, image thumbnails and titles of the artists, movies and serials. Then I am creating a HTML grid from these values.

In the first line of the code I am setting the variable “resultHTML” value as “

Names

” then subsequently appending to it another sets of HTML’s that contains the extracted values form the JSON.

In the end I am showing the value of “resultHTML” inside the “message” div.

You can see I am creating a custom attribute “resourceId” and putting “id” value to it. Later on I will extract this id from jQuery and make another jQuery AJAX call to the API to get the complete information of the resource having this id.
Testing the Application

At this point if you test the application by filling a search text on the text box (example ‘nicole’) and clicking the button. The result will show like this:

IMDB API result

Glad to see my favourite actress “Nicole Kidman” on the first row.

Adding another jQuery AJAX Request

I am showing the JSON result in the HTML grid manner. I also want to create another feature where users can click on grid items (artists, movies, serials) and then he gets the complete information of it.

I want to show this complete information of the clicked item in a “Modal Popup” window and to create this modal I will take the help of Bootstrap.

Check my article on How to use Bootstrap

that helps beginners to get started with it quickly.

Creating the Bootstrap Modal Popup

To create a Bootstrap Modal Popup first do the following two things:

  • 1. Add the “bootstrap.min.css” link in the page head.
  • <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    
  • 2. Give the reference of “bootstrap.min.js” just after the jQuery reference.
  • <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    

    Now add the model HTML code to the page:

    <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">&times;</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>
    

Showing Complete Resource Information in Modal Popup

The Modal Popup is in place, my main work with it is to show complete resource information in it when a user clicks on any resource.

For example – If a user clicks on “Nicole Kidman” then the Modal Popup should show the complete information of “Nicole Kidman”.

If you recall I added the custom attribute “resourceId” to the “result” div. I will now add the click event to the “result” div so that whenever a visitor click on this div then I can make the new AJAX call based on the resource Id.

So I use the jQuery “on” method to create a click event. The “on” method is used because this div is dynamically created.

Now add the below jQuery code to it:

$("#message").on("click", ".result", function () {
    var resourceId = $(this).attr("resourceId");
    $.ajax({
        url: "http://imdb.wemakesites.net/api/" + resourceId,
        crossDomain: true,
        global: false,
        data: {
            api_key: "9c4d2620-32a1-4f4a-abd0-c88b008f383e"
        },
        dataType: 'jsonp',
        success: function (result, status, xhr) {
            $("#modalTitleH4").html(result["data"]["title"]);
            var resultHtml = $("<p class=\"text-center\"><img src=\"" + result["data"]["image"] + "\"/></p><p>" + result["data"]["description"] + "</p>")

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

I have extracted the “resourceId” in the first line of the code “$(this).attr(“resourceId”)” and placed it in the variable “resourceId”.

Then I am making another API call by passing this resourceId to the API url. I get a new JSON from the API response. This JSON contains the complete information of the artist, movie or serial.

The information from the JSON is extracted and –
1. Title is set in the modal header (“modalTitleH4”) area.
2. Extracted image url and description values are set inside the modal body (“modalBodyDiv”) area.

In the end I am showing the Bootstrap modal popup to the user:

 $('#myModal').modal("show");
 

That’s all, if you now click on any artist then the Bootstrap Modal Popup will show you the complete information of that artist.

artist full information in bootstap modal poupup

You can download the codes or view the demo from the links below:

TheMovieDB (TMDB) API is another great API that you can implement to get all actors, movies and series information.

DEMO DOWNLOAD

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.