Clicking on the toggle button will reveal a different ID each time, extracted from JSON links

I have a JSON file containing information about movies currently playing in theaters. I want to display specific details for each movie when its title is clicked, but my code isn't functioning properly. Currently, all the movies' information is displayed regardless of which title is clicked.

My goal is to be able to click on a movie title, such as "Ender's Game," and have only that film's information appear in a designated div. Below is the JavaScript code I am using:

$(document).ready(function() {
    $.getJSON('json/store.json', function(results) {
       //Get movie titles
        for (var i = 0; i < results['results'].length; i++) {
            var title = '<p><a href="#" class="title" data-movie-id="'+i+'">' + results['results'][i].title + '</a></p>';
            $('#movies').append(title);
         }

        //Display movie info on click
        $('.title').click(function(){ 
            var index = $(this).attr('data-movie-id');
            $('#info').empty().append("<p class='biohus'>" + results['results'][index].title + "</p>");
            $('#info').append("<img id='myndbio' width='200' height='300' class='img' src =" + results['results'][index].image + ">");
            $('#info').slideToggle("slow");
        });

});

Below is the HTML code structure:

<div id="bio" class = "content">
        <center><h1 class="cinemaheadline">Movies in Theater</h1></center>

        <div id="movies" class="movies">
            <!-- Movie Titles -->
        </div>

        <div id="info" class="info">
            <!-- Movie Information -->
        </div>
    </div>

The PHP code used to connect to the API is as follows:

   <?php
//check if curl extension is loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");
//API URL
$url = 'http://apis.is/cinema';
$storejson = 'json/store.json';
//write the JSON response to a local file
$fw = fopen($storejson, 'w'); 

$ch=curl_init($url); //initialize curl
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //set options
$r=curl_exec($ch); //execute
curl_close($ch); //close curl

$arr = json_decode($r,true); //decode JSON

fwrite($fw, json_encode($arr, TRUE)); //write to file
?>

Answer №1

The primary issue at hand is the need for a connection between the title and the corresponding information. One solution is to enclose each movie's title and info in its own div, or utilize an attribute like "data-movie" with a distinct identifier to link them together.

If opting for the former approach, you would implement something similar to:

$('.title').click(function(){ 
    $(this).parent().find('.info').slideToggle("slow");
});

Alternatively, the latter method would involve:

$('.title').click(function(){ 
    var dataMovieId = $(this).attr('data-movie-id');
    $('#'+dataMovieId).slideToggle("slow");
});

Furthermore, it is imperative not to misuse IDs as depicted in your current setup, such as assigning identical IDs to multiple img tags. Each ID should be unique on a page.

EDIT: Complete code snippet provided below;

$(document).ready(function() {
    $.getJSON('json/store.json', function(results) {
        for (var i = 0; i < results['results'].length; i++) {
            // Constructing title link with data-id attribute
            var title = '<p><a href="#" data-id="'+i+'">' + results['results'][i].title + '</a></p>';

            // Building info section elements
            var infoTitle = "<p class='biohus'>" + results['results'][i].title + "</p>";
            var infoImg = "<img id='myndbio' width='200' height='300' class='img' src =" + results['results'][i].image + ">";
            // Wrapping title and image within a div using data-id attribute
            var info = '<div class="movie-info data-id="'+i+'">'+infoTitle+infoImg+'</div>';

            // Appending title and info sections appropriately
            $('#movies').append(title);
            $('#info').append(info);
         }
    });

    // Setting up click event handlers
    $('#movies a').click(function(){
        // Extracting data id of clicked movie
        var id = $(this).attr('data-id');
        // Displaying associated movie info based on ID
        $('#info .movie-info[data-id="'+id+'"]').slideToggle("slow");
    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using logical reasoning to upload data with conditional statements in Node.js with required validation

I have an existing schema that I need help with. Here is the structure: const mongoose = require('mongoose'); const position = mongoose.Schema({ startIndex: { type: Number, required: true }, endIndex: { type: Number, required: false }, ...

What is causing my Bootstrap Dropdown Menus to disappear when I work with local files?

I have been utilizing Bootstrap for about a year now, and it has been quite effective. However, I encounter the same issue every time I attempt to use the files locally: my Navbar dropdown menus do not drop down. Could someone pinpoint what mistake I am m ...

Is there a way to modify my code to eliminate the need for a script for each individual record?

Whenever I need to create a code with the ID by browsing through my records, is there a way to make just one function for all the records? $tbody .= '<script> $(document).ready(function(){ $("#img'.$idImage .'").click(functi ...

Tips for removing cookies with Javascript after an allotted period of time

I need to remove a specific cookie value that I set after a certain time period. For example, I want the cookie to be deleted after 10 seconds. function fullday() { document.getElementById("res").innerHTML="1 day"; document.cookie="day="+1; do ...

Efficient management of jQuery variables

I am currently working on a form and I have been trying to change an input's type using jQuery. Thanks to the helpful resources available on this website, I learned that I need to clone and replace the input in order to change its type. However, I enc ...

Ways to retrieve keys from the json object below

Working on integrating handsontable with a php backend, I'm attempting to dynamically generate table column headers. This involves creating an array of column names that will be used in handsontable like so: colHeaders: ['ID', 'First&a ...

Has the jQuery plugin object misplaced a variable?

I am in the process of developing a basic plugin using jQuery. My current approach involves creating private functions and storing variables within the jQuery object itself. (function($) { var somePrivateFn = function() { alert(this.x); } ...

Different strategies for displaying a singular pie chart on multiple pages

I have implemented a pie chart on an HTML page and now I want to display this chart on multiple other HTML pages. Below is the JavaScript code for creating the pie chart: function piechart() { var chart; var legend; ...

Attempting to generate tables from JSON containing numerous "table" sections

Hello there. My goal is to generate tables from the JSON data I've received. While creating a table works fine with a single block of JSON, I face challenges when dealing with multiple blocks for multiple tables. Below you'll find an example of J ...

Building Your Initial HTTP Server using Node.js

Hey everyone, I'm relatively new to node.js but have made some progress. Following the steps in this tutorial, I was able to create my first "example" server. However, there are a few things that I don't quite understand. Could someone please exp ...

Tips on using b-table attributes thClass, tdClass, or class

<template> <b-table striped hover :fields="fields" :items="list" class="table" > </template> <style lang="scss" scoped> .table >>> .bTableThStyle { max-width: 12rem; text-overflow: ellipsis; } < ...

Toggling checkboxes based on user input

My dynamic table is filled with checkboxes that can be checked or unchecked. I have created a jquery script that should change the background color of the table cell whenever a checkbox is modified. However, the script seems to have some bugs and doesn&apo ...

assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable? I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose. I attempted using jQuery to achieve this, and it works well with a fixed ...

Perl and JSON are used to handle floating point numbers in a structured format

Our Perl application generates JSON data from DB queries, but it mishandles float values by enclosing them in double quotes. For example: use DBI; use JSON::MaybeXS; my $dbs="dbi:ODBC:myconnection,myuser,mypwd,"; my @ARR=split/,/ ,$dbs; $dbh = DBI->c ...

Developing with Angular 1.4.8 and JavaScript involves the process of building a constructor function to inherit properties into a third object

DEVELOPER TOOLS Using Angular 1.4.8 and lodash QUERY: REVISIT To clarify my query: Create an object (articles) Apply a constructor Import the properties of a third object, but place it in proto folder to prevent cluttering the root with a large colle ...

Generating Placeholder Variables Within a v-for Iteration

Encountering a problem with Vue-JS involving v-for loops and v-model properties. I have an array of items: <input v-for="i in list" v-model="i.model" ... (other tags that use i) > </input> Accompanied by some JavaScr ...

Utilize key value pairs to retrieve data from a multi-level array

I'm looking for assistance with extracting values from an array based on key value rather than array number. $json = json_decode($stock, true); print_r($json); $sims = $json['stock'][1]['sims']; foreach ($sims as $sim) { echo ...

What is the best way to retrieve the value from a JSON object when the key contains

Hi there! I am looking to retrieve the value of a key within a nested JSON structure. Below is the JSON snippet: Take a look at my JSON data: { "errors": { "products.2.name": { "name": "ValidatorError", ...

Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements: list = [ {header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""} ] My que ...

Passing JSON information through PatternLab

Incorporating an atomic pattern and passing data from a JSON array is my goal. Below are the code snippets and JSON file. anchor-link.mustache <a href="{{ url }}" class="{{ class }}">{{ label }}</a> footer-nav.mustache <ul class="menu ve ...