0

Im trying to update the src from the audio tag if i click on a button. So i need to translate the $muziek variable to Jquery

View:

<?php
    foreach ($muziek as $ms)
    {
        if ($ms->id == 2) {
            echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
            echo '</audio>';
        }
    }

    foreach ($muziek as $ms)
    {
        echo '<br>';
        echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
    }
?>
</div>

<script>
    $("input").click(function () {
       var test = $(this).attr("id");
       console.log(test);
       //Here needs to be the foreach muziek       
    });
</script>

Muziek variable: This is how i fill the music variable

function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    return $muziek;
}

Does someone has an idea or show me how this can be done?

treyBake
  • 6,440
  • 6
  • 26
  • 57
arnekick
  • 43
  • 7
  • 1
    a keyword to google: **ajax** – treyBake May 28 '19 at 09:57
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – treyBake May 29 '19 at 07:51

2 Answers2

0

I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:

$.get( "base_url/your_controller/getAllMuziek" )
    .done(function( muziek ) {
        //Here needs to be the foreach muziek     
        $.each(muziek, function( index, value ) {
            // whatever
        });
    });

with a simple modification to your method getAllMuziek:

function getAllMuziek()
{
    $query = $this->db->get('muziek');
    $muziek = $query->result();

    header('Content-Type: application/json');
    echo json_encode($muziek);
}

now when you make you ajax call you will get your result.

Sherif Salah
  • 2,085
  • 2
  • 9
  • 21
-1

Convert $muziek into javascript array using json_encode

<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>
Thi Tran
  • 681
  • 5
  • 11
  • I get this when i do console.log() Uncaught SyntaxError: Unexpected token ; – arnekick May 28 '19 at 10:11
  • 1
    using PHP in JS in like this (and vice versa) is extremely bad practice. – treyBake May 28 '19 at 12:41
  • @treyBake: I know how to use ajax request and of course it's better, but in this case, this guy seems to be very junior so I think it's not a bad solution for him :) – Thi Tran May 29 '19 at 03:32
  • why would you teach a junior something bad for them later to re-learn the right way? o.O – treyBake May 29 '19 at 07:50