0

I have a button created with Jquery and Ajax refreshed every second.

I want to send an empty Get/POST request to trigger my API.

I couldn't manage to select created buttons with Jquery.

Any idea's how can I achieve this?

I'm sharing my codes below

$(document).ready(function(){

function fetch_openorderdetails()
 {
  $.ajax({
   url:"/api/v1/open-orders/1",

   dataType:"json",
   success:function(details)
   {
    var html = '';

 for(var i=0; count < details.length; count++)
 
    {
      var id = details[i].id
      var currentvalue = details[i].price;
      html += '<button class="btn btn-danger" id="sellbutton_'+ id +' " >SELL ($'+currentvalue+')</button>';  
      //with this button I want to send empty GET/POST request to my api trough URL. (ie: /sell/{id} )
     }
     
    $('#all-open-orders').html(html);
    }
    
setInterval(function(){fetch_openorderdetails()}, 1000);

    
<div class="row" id="all-open-orders">
 
 </div>

I want to trigger below function when button clicked .

If possible I want to also pass the id from button to this function

$("sellbutton").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/sell_trigger_by_OID/7532", //if possible I want to get 7532 with a variable from the clicked button
        data: { 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});
https://stackoverflow.com/posts/68971743/edit#https://stackoverflow.com/posts/68971743/edit#

Any idea much appreciated

  • You need to delegate. Where is the sellcode? give the button a class, then you can delegate using `$('#all-open-orders').on('click','.sellbutton',function(e) {})` – mplungjan Aug 29 '21 at 09:54
  • @mplungjan This helped me to do a workaround thank you I want to trigger a different URL with each button How can I pass it from the clicked button ? – Fannie Johnson Aug 29 '21 at 10:07
  • Use a data-attribute and read it using `$(this).data(“attribute name”)` – mplungjan Aug 29 '21 at 10:22
  • `success:function(details) { const html = details.map(({price.id}) => \`\`).join(""); $('#all-open-orders').html(html); }` – mplungjan Aug 29 '21 at 12:34
  • Also I recommend moving `setTimeout(fetch_openorderdetails, 3000);` to the success instead of using interval. Also why would you run this EVERY second? – mplungjan Aug 29 '21 at 13:10

0 Answers0