March 16, 2015 9:32 am

How to Reward users for viewing videos using AJAX

In this project, we are going to show you how to reward users for watching videos in your site. They would be rewarded only for watching the whole video without fast-forwarding/skipping parts of it and would be rewarded only once for each video.

How to Reward users for viewing videos using AJAX

[wpdm_file id=130]DEMO

Details:

we are not going to implement the back-end of the app, so we are going to use a static json file with list of videos, we are going to show all videos from the json through a XHR and we are going to give 50 points for each watched video.

Since we are not going to implement the back-end we will store the points the user has up to now and an array of all videos the user has already watched in localStorage. You might implement the back-end in any way you want.

We would not be using any framework or library, just vanilla JavaScript

The code

Firstly, we simulate a JSON response from our server

api.json

{

    "videos" : [
      "appVideos/us-combat.mp4",
      "appVideos/steam-whistle.mp4",
      "appVideos/panorama.mp4" 
    ]
}

Then, we create our page and set up some basic styling.

#messages is the element where we would write that the user has earned points or that he already watched that video so no points would be given to him.

#video-wrapper is the element where we will load our video paths through AJAX.

<!DOCTYPE html>

<html>
    <head>
        <title>Video App</title>

        <meta charset='utf-8'>

    <style>
        body {
            width: 960px;
            margin: 0 auto;
            text-align: center;
        }
        h1,h2 {
            font-family: "Comic Sans MS";

        }

        #video-wrapper video {


            border: 4px groove crimson;
        }


    </style>

    </head>

    <body>
        <div id='messages'>
            <h1>Watch videos and earn points.</h1>
        </div>
        <div id="video-wrapper"> 
    <script>
                var points = parseInt(localStorage.points, 10) || 0;
                var watched = localStorage.watched || [];
                if (typeof watched !== "object") {
                    watched = JSON.parse(watched);
                }

We set up the points to be equal to the current points stored in localStorage or set them up to 0 if localStorage.points is undefined.

We initialize the watched videos variable. We then check if it is an object(because localStorage stores text only and if it is not an object (the empty array) it would be a string) and if it is not an object we parse the localStorage’s string as JSON.

We set up a handler for when the DOM is ready – ` window.onload = function() { and inside it make an ajax call:

var xhr = new XMLHttpRequest();
                xhr.onload = reqListener;
                xhr.open("get", "api.json", true);
                xhr.send(); 

We fetch api.json and execute the reqListener function whenever the request is complete.

Then, we parse the responseText as json and loop through each video adding it to the DOM.

We add an ‘ended’ event listener for each video and check if this.played.length is equal to 1. It would be 1 only when the user has watched the entire video.

If he has watched the entire video, we check if that video source is already in the array, and if it is we give him a message that he has already watched it. If it is not in the array, we add it to the array, give him points and a congratulatory message.

That is all there is to it. Now, you can take advantage of this and implement it in serious projects.

function reqListener () {
                    var videoSrc,video, response = JSON.parse(this.responseText);
                    for (var i = 0, x = response.videos.length; i < x; i++) {
                        videoSrc =  response.videos[i];

                        video = document.createElement("video");
                        video.setAttribute("id", videoSrc);
                        video.setAttribute("src", videoSrc);
                        video.setAttribute("controls", "controls");
                        document.getElementById("video-wrapper").appendChild(video);

                        document.getElementById(videoSrc).addEventListener("ended", function() {

                            if (this.played.length === 1) {
                                if (watched.indexOf(this.id) === -1) {
                                    points += 50;
                                    localStorage.points = points;
                                    watched.push(this.id);
                                    localStorage.watched = JSON.stringify(watched);
                                    document.getElementById("messages").innerHTML += "<h2>You watched a new video. +50 pts -> Points so far:" + points + "</h2>";

                                }
                                else {
                                    document.getElementById("messages").innerHTML += "<h2>No points for ya this time, mate. You already watched this :( </h2>" ;
                                }


                            }
                        })
                    }




                }

I hope it helps you please do share it. If you face any problem write in comments.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

3 responses to “How to Reward users for viewing videos using AJAX”

  1. habib says:

    Really nice tutorial.thanks

  2. Wangdu Ravi says:

    Nice Tutorial, can you write a tutorial on Video Content Locker.
    I mean the Previous post I saw was “Social Content Locker”, so in same way can you make a Video Locker. A visitor have to View atleast a minute to access the Content.

    Thank You…

Leave a Reply

Your email address will not be published. Required fields are marked *