Extracting text from URL using $_GET gives me undefined

Viewed 47

I'm trying to extract an id from get-albums-genres.php?gid=".$id." using $_GET and it gives me undefined!

I fetched data for music genres in an array after running an SQL query to extract data from my genre table

$dbcursor = $db->query("
    SELECT *
    FROM GENRES_TBL
    ORDER BY ID
    ");

$genres = [];
while($takegenre = $dbcursor->fetch_object()) $genres[] = $takegenre;

After this I created a html table containing <a tags with hyperlinks for each genre using foreach loop.

    <?php
    foreach($genres as $gs)
    {
        $id = $gs->ID;
        echo "
            <a class='gentons' href='get-albums-genres.php?gid=".$id."'>".$gs->GENRE."</a>";
    }
    ?>
</table>

With these hyperlinks I want to show table of all albums from selected genre. In order to do that i plan to extract the id from the href and than use it in an SQL query to connect the albums genre id to the genres ids, BUT in the php file for getting the albums when declaring the variable and using $_GET to extract the id it gives me undefined value.

$genre_id = $_GET['gid'];

echo"$genre_id";   //undefined

if(isset ($_GET['gid'])){
    echo"yes";
}else{
    echo"no";
}  //yes

The Javascript code with the event is

 $(document).on('click', 'a.gentons', function(e)
            {
            $.get('get-albums-genres.php?gid=' + $('input[name="gid"]').val(),
            function(data)
                {
                $('#albums-list').html(data);
                });
            return false;
            })

It's strange because i did exactly the same in another php file where i input name or best-song of an artist and find and show all his albums and i have no problems with the $_GET method there. I also don't understand why when i hover my cursor over the hyperlinks for the genres it show the link and the corresponding id, but when i try to extract it there is a problem

enter image description here

1 Answers

You've got a couple of problems here. First, instead of using the href in your link tag (you never want anyone to actually visit that URL, right?), let's set the href to # and put our genre ID in a data attribute. Let's get our single/double quotes straight while we're at it.

echo '<a class="gentons" data-gid="' . $id . '" href="#">' . $gs->GENRE . '</a>';

Now in our JS, we can cancel the event with preventDefault(), grab the genre ID, and everything else stays the same.

$(document).on('click', 'a.gentons', function (e)
{
    e.preventDefault();
    
    $.get('get-albums-genres.php?gid=' + $(this).data('gid'),
        function (data)
        {
            $('#albums-list').html(data);
        });
    
    return false;
});

This should work, or at least get you to your next bug.

Related