How to pass variable to AJAX?

Asked

Viewed 262 times

0

I have a screen where I list several songs and next I have an image that calls AJAX to add this song playlist. My doubt is how to pass the ID of this song to AJAX, since I can’t use the URL, because this has to be with #.

    while($consulta2 = mysql_fetch_array($result2))
    {; 
      echo"<div class='album-musicas'><a href='musica.php?musica=$consulta2[id_musica]&artista=$consulta2[id_cantor_fk]&album=$consulta2[id_album_fk]' class='album-musicas-texto'>$consulta2[nr_faixa].  $consulta2[nm_musica]</a>";
      if ($consulta2["nm_som"] != '') { 
        echo "<a href='#' id='add-musica-playlist-link'>
        <img src='images/button-add-13.png' title='Adicionar à playlist' ></a>";
      }
    echo "<br><div class='separador-musica'></div></div>";    
    }

1 answer

0


I believe it is the case to print, from PHP itself, the music code on the add button. But before, only one thing I noticed: it is id or class, in the first line of the section below?

echo "<a href='#' id='add-musica-playlist-link'>
      <img src='images/button-add-13.png' title='Adicionar à playlist' ></a>";

I believe you want to switch to class; but anyway, this is not related to your question. Let’s get to 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 (data Attributes), if you are dealing with HTML5; injection of data into elements other than the <input />; etc..

Anyway, once served the data via PHP, comes the part of Javascript to collect them -- IE, look for them in the DOM. Within the element <a> of each "Add to playlist" button, there is a <input /> Hidden which contains the music code. Therefore, in the function of callback of your Listener of each button, there should be something like this:

(The HTML had to be slightly modified relative to the above markup, but the JS code fits 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 section should have no problems to run on IE9 and other more modern; if you implement another type of Listener more compatible, probably this code is able to run in very old browsers :)

Note that this JS is tied to my PHP suggestion; other markup types require modifications to the DOM search performed by Javascript, so don’t forget to hack this code until you can extract your ID to AJAX.

  • thank you! There is ID even, it calls a function jQuery. I didn’t know that had to insert an input Hidden in a <a href>. I’ll test and anything I tell you... Abs

  • add an Alert into this JS just to see if it was really calling correctly, and nothing appears.. Abs

  • I changed some things and now it shows the first Alert "OK", sign that is entering, but the second does not show, sign that is not recovering the value of Hidden: Document.getElementById("add-musica-playlist-link"). addeventlistener("click", Function(e){ Alert(OK); var musica_id = e.srcElement.parentElement.getelementsbytagname("input")[0]. value; Alert(musica_id); });

  • The only problem is that this code is inside a while, that is, it can have more than 1 Hidden input, and in this case only the first one is working. Is it because they have the same ID? Vlw

  • It’s definitely because of the ID, Ricardo :) Exchange for class, as I called attention at the beginning of my reply, and then adjusts Javascript to search by class (getElementsByClassName("classeBotaoAdicionar")) that will work! Just don’t forget that this method returns a LIST of found elements, you will need to iterate and add the Systener to each one!

  • Ah, now I understand, I think the problem is in treating this LIST, because either ID or CLASS only changes the type of the search, the answer is the same, right?

  • I apologize, Ricardo, for the mistake: there was actually a mistake, which was not evident in the test I did because there was only one element with Listener. There was one left parentElement within the function of callback. I took advantage and rewrote the excerpt to work with class instead of id. I hope it helps! Hugs!

  • I switched to CLASS, I did exactly how you rewrote it, it brings the buttons.length = 3, but just doesn’t get into FOR.. Hugs

  • Maybe the i is being used in the middle of the Listener, for another purpose, and thus disturbing the loop... Or doesn’t it really enter? Have you tried doing for(var i = 0; i < botoes.length; i++) console.log(botoes[i]); to test?

  • Worse than not using i. I tested: for(var i = 0; i < buttons.length; i++) Alert(i); and he gave 0 1 2, straight...

  • Experiment with the console.log, which does not interfere with the program flow, and hovering over the printable elements (at least in Chrome) you can see if you have selected the right guys :D But anyway, the example now works and is closer to your case... If necessary, open another question with this new problem, beauty? :)

  • Thanks! I will post a new question... Abs and Thanks

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.