I think it's the case of printing, from PHP itself, the code of the song in the add button. But before, just one thing I noticed: is id
or class
, in the first line of the passage below?
echo "<a href='#' id='add-musica-playlist-link'>
<img src='images/button-add-13.png' title='Adicionar à playlist' ></a>";
I think you want to switch to class
; but in any case this is not related to your question. Let's face it: the modification you would have to do would be something like:
echo "<a href='#' class='addMusicaPlaylistLink'>
<input type='hidden' value='$consulta2[id_musica]' />
<img src='images/button-add-13.png' title='Adicionar à playlist' ></a>";
To be frank, there are several other ways to serve the data (in this case, the music ID in the database) to the client side: data attributes ), if you is dealing with HTML5; injection of data into elements other than <input />
; etc.
Anyway, once the data is served via PHP, the part of the JavaScript comes up to collect them - that is, search for them in the DOM . Within the <a>
element of each "Add to playlist" button, there is a% co hidden containing the song code. So in the callback function of your listener of each button, there should be something like this:
(The HTML had to be slightly modified over the above markup, but the JS code is for both cases.)
// Aqui é apenas um exemplo de como adicionar o listener a todos os botões:
var botoes = document.getElementsByClassName("addMusicaPlaylistLink");
for(var i = 0; i < botoes.length; i++) botoes[i].addEventListener("click", function(e){
// ...
// Este trecho busca o código da música cujo botão foi clicado:
var musica_id = e.srcElement.getElementsByTagName("input")[0].value;
// ...
// Hora do AJAX! O ID da música estará na variável 'musica_id'!
// ...
// O trecho abaixo simplesmente mostra o código capturado, por motivos didáticos:
var p = document.createElement("p");
p.innerHTML = "O usuário requisitou que a música " + musica_id + " fosse adicionada à playlist.";
document.body.appendChild(p);
});
<a href='#' class='addMusicaPlaylistLink'>
<input type='hidden' value='1234' />
Adicionar música 1234
</a>
<br />
<a href='#' class='addMusicaPlaylistLink'>
<input type='hidden' value='1235' />
Adicionar música 1235
</a>
The above excerpt should have no problems running in IE9 and other more modern ones; if you implement another type of listener more compatible, this code is probably able to run in very old browsers:)
Note that this JS is tied to my suggestion in PHP; other markup types require modifications to the DOM fetch performed by JavaScript, so do not forget to hack this code until you can extract your AJAX ID.