Put php variable to ajax depending on the name of the class and the content

0

The title does not explain much, but I have a code that gives a number to the class, because it is in foreach , it would be

<button class='accept ".$accept++."'>Accept</button>

the $ accept ++ is added one for each time it passes through the foreach, and I want that if you click on the button an ajax request is sent with the content of the row:

It is explained like this: If I have the name Juan and accept 1, I want you to send a request with that information, then it would be Luis and accept 2, etc ...

AJAX:

$( ".accept" ).click(function() { // aqui quiero el accept 1, accept 2...
     $.ajax({
         type: "POST",
         url: "url.php",
         data: {'nombre':'<?php echo $nombre; ?>'}, //el nombre del row sacado con foreach
         success: function(){
             console.log("Yes");
         },
         error: function(){
             console.log("error");
         }
    });
});
    
asked by Aspoky 11.07.2018 в 03:26
source

2 answers

0

You can perfectly assign the same class to the buttons, not an incremental class , create a listener for the buttons of that class, and then through this you can get any data from the button that was pressed.

For example:

$('button.my-buttons').click(function() {
  var $btnId = $(this).prop('id');
  var $btnName = $(this).prop('name');
  var $btnValue = $(this).prop('value');
  var $btnClass = $(this).prop('class');
  var $btnText = $(this).text();

console.log('ID: ${$btnId} | name: ${$btnName} | value: ${$btnValue} | clase: ${$btnClass} | texto: ${$btnText}');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-buttons" id="btn1" name="Nombre1" value="valor1">Botón 1</button>
<button class="my-buttons" id="btn2" name="Nombre2" value="valor2">Botón 2</button>
<button class="my-buttons" id="btn3" name="Nombre3" value="valo3">Botón 3</button>
    
answered by 11.07.2018 в 04:04
0

Why do not you try with the following. You create an ID to each button and from js you recover it and you already send it with ajax:

<button class='acceptbtn' id= "'.$accept++.'">Accept</button>


$( ".acceptbtn" ).click(function() {
     //Recuperas el ID del botón cliqueado
     var id = $(this).attr('id');
     //Creas una variable, y le agregas el id recuperado
     var datos = new FormData();
     datos.append("id",id);
     //Envías los datos por ajax.
     $.ajax({
         type: "POST",
         url: "url.php",
         data: datos,
         success: function(){
             console.log("Yes");
         },
         error: function(){
             console.log("error");
         }
    });
 });

I hope it works for you. Greetings.

    
answered by 11.07.2018 в 05:07