-4

I have a variable that holds the value of a checked checkbox. I need to pass it to a PHP file as a PHP variable so that I can run a query with it. I was told I could achieve this with AJAX but I have no knowledge on it and very little time. I would really really appreciate some help!

<script>
function checked(){
var chkbxElements = document.getElementsByClassName("checkboxes");
  for (element of chkbxElements){
    if (element.checked)
      return element.value ;
    } 
  return null;
}

var element = checked();  //pass it to a php file

I tried the code below but it doesn't work.

      $.ajax({
      method: "POST",
      url:"file.php",
      data: {id: element},
      success: function(data){}
    })
 
     </script>

    <?php 
     $id = $_POST['id'];
     ?>
Cedi
  • 9
  • 5
  • Your `for` loop will return at the first checked checkbox regardless of how many are checked. – Jared Smith Jan 17 '21 at 22:15
  • @JaredSmith No, I need the value before submitting it. And the checked() function works okay that's the way it was intended – Cedi Jan 17 '21 at 22:18
  • Submitting what? There's no form in your code. Also, so what? There's nothing about the answers on that linked duplicate that preclude storing the value someplace. What is your question exactly? – Jared Smith Jan 17 '21 at 22:19
  • Okay so I have a bunch of checkboxes and when I click on one of them it's supposed to get the value of it, run a query with it, and display a table that's the result of that query. – Cedi Jan 17 '21 at 22:21
  • Ok, that's more clear. But again, what is unclear about the answers on that linked duplicate question? – Jared Smith Jan 17 '21 at 22:25
  • I don't really get it – Cedi Jan 17 '21 at 22:28
  • 1
    Ok that's fine, but in that case I suggest you go work your way through some tutorials or pay/beg someone more experienced to mentor you. We aren't really set up to teach web development here. – Jared Smith Jan 17 '21 at 22:35

1 Answers1

1

Since you are confident that you got the right element (the string data of the value attribute) only the AJAX part needs to be demonstrated here:

// jQuery:
$.ajax({
  method: "POST",
  dataType: "JSON",
  url:"https://jsonplaceholder.typicode.com/posts",
  data: {uploadData: "my jQuery payload"},
  success: function(data){
    console.log(data);
  }
})

// Vanilla:
fetch("https://jsonplaceholder.typicode.com/posts",
 {method: 'POST',
  body: JSON.stringify({
   uploadData: 'my Vanilla-JS payload'}),
  headers: {'Content-type': 'application/json; charset=UTF-8'
 }})
  .then(r=>r.json())
  .then(j=>console.log(j))
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Obviously, I had to use some other backend server to send the data to but it should work with your own backend just es well.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43