Send JS variable to PHP script via ajax on click of button where the href attribute is set dynamically

Advertisements

This is the current situation:

  • I have one checkbox on each row of a table representing some infos
  • A button that is initially disabled and if any checkbox is checked it gets enabled
  • This button is wrapped/enclosed by an <a></a> tag like this <a><button type="button" id="myId" classes="classes..."></button></a>
  • An array which is initally empty

Suppose I have 10 rows (so 10 checboxes, one for each row) eveytime I check a checkbox I push into the array some info represented inside the table and I enable the disabled button (even with 1 checkbox the button gets enabled)

At this point what I want to do on the click event of the enabled button is to set the href attribute and a link to a PHP file on the <a> tag that is wrapping the button and secondly to send via ajax that array which contains info from the table.

I tried to do it this way but it does not seem to work:

 $('#my_initially_disabled_button').on('click',function(){
   if(some_generic_flag == true){
      let link = this.parentNode;
      link.setAttribute('href','scripts/php_script.php');
      
      $.ajax({  
        type: 'POST',  
        url: 'php_script.php', 
        data: { data: my_array }, // my_array is that array which gets update each time a checkbox is checked
        success: function() {
            //some stuff;
        }
    });
   }
});

I also tried to make write the ajax part outside of the on click event but still is not working the result I get is a blank page….

The interesting fact is that if I remove the ajax part it redirects me correctly to the PHP file and correctly echoes stuff.

In the PHP I tried to receive the ajax request like this

 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     $var = $_POST['data'];
     
     // if I do var_dump($var) it does not work
}

>Solution :

  • Remove the link from the button – it is invalid and unnecessary.
  • grab the checked info when clicking the button
$(function() {
  const $button = $("#send");
  let array = [];
  $("#container").on("input", () => {
    array = $(".info:checked").map(function() {
      return this.value
    }).get();
    $button.prop("disabled", array.length === 0);
  });
  $button.on("click", () => {
    const data = JSON.stringify(array);
    console.log(data)
    // $.ajax(...., data:data, ....)
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <label>info1 <input type="checkbox" value="info 1 data" class="info" /></label><br/>
  <label>info2 <input type="checkbox" value="info 2 data" class="info" /></label><br/>
  <label>info3 <input type="checkbox" value="info 3 data" class="info" /></label><br/>
  <button id="send" disabled>Send</button>
</div>

Leave a ReplyCancel reply