Search code examples
jqueryjquery-templates

How to put data of JSON-array with square brackets into JQuery Template


How do I acccess the different attributes in the objects of this json-data inside a JQuery Template?

Input json data:

 `[ [ [ "Title", "Awakening Now" ], [ "Date", "2012-05-25" ], [ "VideoDescription", "Test video awakening now" ], [ "Language", "english" ], [ "Category", "special" ], [ "VideoLink", "http://www.premanandasatsangtvarchive.org/international/2013-05-25enL.mp4" ], [ "HDLink", "http://www.premanandasatsangtvarchive.org/international/2013-05-25en.mp4" ], [ "PosterFrame", "http://www.premanandasatsangtvarchive.org/archive/images/2013-05-25.jpg" ], [ "id", "2" ], [ "TitleGerman", "testtitlegerman" ], [ "SubtitleGerman", "testsubtitlegerman" ] ], 

[ [ "Title", "Glimpses of Our True Nature." ], [ "Date", "2012-05-16" ], [ "VideoDescription", "testvideo glimpses" ], [ "Language", "english" ], [ "Category", "archives" ], [ "VideoLink", "http://www.premanandasatsangtvarchive.org/international/2012-05-18enL.mp4" ], [ "HDLink", "http://www.premanandasatsangtvarchive.org/international/2012-05-18en.mp4" ], [ "PosterFrame", "http://www.premanandasatsangtvarchive.org/archive/images/2012-05-18.jpg" ], [ "id", "1" ], [ "TitleGerman", "test" ], [ "SubtitleGerman", "test" ] ] ]`

Javascript:

$.ajax({
      url: 'scripts/videodatabasehandler.php',
      type: 'post',
      data: {'language': lang},
      success: function(data, status) {
        var sattv=jQuery.parseJSON(data);


         // Render the books using the template
        $("#videoTemplate").tmpl(sattv[0]).appendTo("#videoContainer");

         if(data == "ok") {
            console.log(data);
          alert("hallo"+data);
        }
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call
  });

Code for JQuery Template and html:

   <div id="videoContainer"></div>



      <script id="videoTemplate" type="text/x-jQuery-tmpl">
            <div class="date">${Date}</div>
            <br/>
                <div class="title">${Title}</div>
            <br/>
            </div>
            <video id="2013-05-25en" class="sublime" data-initial-overlay-enable='false' 
            poster="http://www.premanandasatsangtvarchive.org/archive/images/2013-05-25.jpg" 
            width="100%" title="EN Changes" data-uid="2013-05-25en" preload="none">
      <source src="http://www.premanandasatsangtvarchive.org/international/2013-05-25enL.mp4" />
      <source src="http://www.premanandasatsangtvarchive.org/international/2013-05-25en.mp4" data-quality="hd" />
        </video>    
        <br /><br />
        New item..

        </script>

Example page: http://www.premanandasatsangtvarchive.org/sattv/sattvresponsive/datatables-1.10.2/examples/server_side/videoarchives.html


Solution

  • The problem is that your json with the list of movies contains the fields in an array so what you get for each movie with jQuery.parseJSON(data); is an array of fields where each fields is itself an array with 2 items fieldName and Value. Your server is not sending an array of json objects where each field in the json is a property of the movie!

    For example, if you log your first video with console.log(sattv[0]); you will see something like this in the console:

    [Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]

    To find the title you would need to access the first array in the video, and then its second element as in console.log(sattv[0][0][1]).

    It would be hard to work that way in the templates (and error prone, since your code would rely on the order of the fields), so you can convert these arrays into proper json objects. You could write some code that will go through the arrays converting your initial sattv into a proper array of movies json objects:

    var getMovies = function(moviesArray){
        var movies = [];
        if(!moviesArray || !moviesArray.length) return;
        $.each(moviesArray, function(index, elem){
            movies.push(getSingleMovie(elem));
        });
        return movies;
    }
    
    var getSingleMovie = function(fieldsArray){
        var movie = {};
        if(!fieldsArray || !fieldsArray.length) return;
        $.each(fieldsArray, function(index, field){
            movie[field[0]] = field[1]; //example: movie["Title"] = "Awakening Now"
        });
        return movie;
    }
    

    This way you can do var movies = getMovies(sattv); and now if you have a look at movies[0] you will notice that it is a proper json object and you can access its properties by name as in movies[0].Title.

    So you could now render the first movie using the converted objects as in:

    $("#videoTemplate").tmpl(movies[0]).appendTo("#videoContainer");
    

    I have created a fiddle so you can give it a try.