Home > Software engineering >  JSON select data at specific ID
JSON select data at specific ID

Time:11-07

In PHP, I've created a function to create a JSON file:

function writeJSONData(PDO $conn): void
{
    $contentJSON = "SELECT * FROM tb_content";
    $contentResultsJSON = $conn->query($contentJSON);

    $contentJSONExt = array();

    while ($JSON = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC)) {
        $contentJSONExt = $JSON;
    }

    $infoJSON[] = json_encode(array('movies' => $contentJSONExt));
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . "/CineFlex/private/api/api.json";

    file_put_contents($target_dir, $infoJSON);
}

In my HTML file I've created a button which sends the ID of the selected movie:

<!-- Edit Button -->
<button onclick="toggleDialog(editMovie, this.id)" id="<?php echo($info['content_id']) ?>Edit Movie</button>

My JavaScript file contains the function:

// Toggle Dialog
function toggleDialog(dialogName, dialogID) {

    // Toggle Dialog Visibility
    $(dialogName).fadeToggle(200);

    $.getJSON("./private/api/api.json", function (data) {
        console.log(data)
    })
    
}

When I click on the edit button, it prints the entire JSON file in the console. Which is understandable.

Current output:

{
    "movies": [
        {
            "content_id": 15,
            "title": "Scream (2022)",
            "description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."

        },
        {
            "content_id": 16,
            "title": "Fear Street: Part Two - 1978",
            "description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
        },
        {
            "content_id": 17,
            "title": "Archive 81",
            "description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
        }   
    ]
}

Now my issue is, I want the "dialogID" to be selected from the JSON file where it matches with "content_id". For example: When I click on a movie with 16 as "dialogID", I want the console to just print everything from that array.

Expected output:

{
    "movies": [
        {
            "content_id": 16,
            "title": "Fear Street: Part Two - 1978",
            "description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
        }
    ]
}

Edit: A friend of mine helped me figuring this out. Thanks everyone!

CodePudding user response:

To get it, you need to create dynamic API instead of static file content. In alternative case, you can get it only from JS loop (check all and check suitable ID). If you want to do it with API, you must change html and php script like this:

function getDataById(PDO $conn):string
{
    $id = (int) $_GET['id'];
    $contentJSON = "SELECT * FROM tb_content where id = :id";
    $contentResultsJSON = $conn->prepare($contentJSON);
    $contentResultsJSON->execute([':name' => 'David', ':id' => $_SESSION['id']]);
    $rows = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC);
    
    $contentJSONExt = array();

    while ($JSON =$rows) {
        $contentJSONExt = $JSON;
    }

    return json_encode(array('movies' => $contentJSONExt));
}

And, JS codes to change like this:

// Toggle Dialog
function toggleDialog(dialogName, dialogID) {

    // Toggle Dialog Visibility
    $(dialogName).fadeToggle(200);

    $.getJSON("https://my-site.com/getDataById/?id=" dialogID, function (data) {
        console.log(data)
    })
    
}

CodePudding user response:

I don't know if you want to select in your php the right ID, and send back only the right one or if you want the whole json back and select in javascript.

First answer here gives the answer to dynamic php: only the right ID back from server.

I will try to answer the second possibility: all json movies back, selection in javascript.

html (3 buttons for example):

<button onclick="toggleDialog(this.id)" id="15">Edit Movie 15</button>
<button onclick="toggleDialog(this.id)" id="16">Edit Movie 16</button>
<button onclick="toggleDialog(this.id)" id="17">Edit Movie 17</button>

javascript, let say we have back the whole json movies, I put a variable here (it's supposed to be the whole json back from php):

let json = {
        "movies": [
            {
                "content_id": 15,
                "title": "Scream (2022)",
                "description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."

            },
            {
                "content_id": 16,
                "title": "Fear Street: Part Two - 1978",
                "description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
            },
            {
                "content_id": 17,
                "title": "Archive 81",
                "description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
            }
        ]
    }

javascript function:

function toggleDialog(dialogID) {
        dialogID = parseInt(dialogID);
        json.movies.every(e => {
            if (e.content_id === parseInt(dialogID)) {
                console.log(e.content_id);
                console.log(e.title);
                console.log(e.description);
                return false;
            }
            return true;
        })

    }

You iterate through the json.movies (it's an object) with "every" instead of forEach. With every, you can break the loop when condition is met dialogID === content_id with return false. You have to put return true at the end of the loop otherwise it breaks immediately.

Your content_id are numbers, so parseInt on the dialogID. If coming from php json, it'll normally be string so no need for that.

CodePudding user response:

Thanks everyone for the help! A friend of mine helped me out:

// Toggle Dialog
function toggleDialog(dialogName, dialogID) {

    // Toggle Dialog Visibility
    $(dialogName).fadeToggle(200);

    $.getJSON("./private/api/api.json", function (data) {
        for (let i = 0; i < data['movies'].length; i  ) {
            if (data['movies'][i]['content_id'] == dialogID) {
                $('#editMovieTitle').val(data['movies'][i]['title'])
            }

        }
    })
    
}
  • Related