lundi 18 février 2019

how to handle data from multiple checkboxes and multiple submits with ajax

I am trying to post data from multiple checkboxes with several submit buttons. Important is: the submit buttons are not part of the form because they are on a different place on the website.

This is what i have so far:

<form class="checkboxform" action="" method="post">
   <input type="checkbox" name="check_list[]" value="C/C++"><label>C/C++</label><br/>
   <input type="checkbox" name="check_list[]" value="Java"><label>Java</label><br/>
   <input type="checkbox" name="check_list[]" value="PHP"><label>PHP</label><br/>
</form>

The submit buttons:

<button type="button" id="delete" name="delete" onclick="submitForm()" value="Delete"/>Delete</button>
<button type="button" id="move" name="move" onclick="submitForm()" value="Move"/>Move</button>
<button type="button" id="copy" name="copy" onclick="submitForm()" value="Copy"/>Copy</button>

The ajax:

function submitForm(url){
   var data = $(".checkboxform").serialize();
   $.ajax({
    type : 'POST',
    url  : url,
    data: data,
    success :  function(data){
        $(".echo").html(data);
       }
   });
};

The php:

if($_POST['delete']) {
  if(isset($_POST['check_list'])){//to run PHP script on submit
    if(!empty($_POST['check_list'])){
    // Loop to store and display values of individual checked checkbox.
        foreach($_POST['check_list'] as $selected){
        echo $selected."</br>";
        }
        // code for delete goes here
        echo 'Files are  deleted!';
    }
  }
}

if($_POST['move']) {
  if(isset($_POST['check_list'])){//to run PHP script on submit
    if(!empty($_POST['check_list'])){
    // Loop to store and display values of individual checked checkbox.
        foreach($_POST['check_list'] as $selected){
        echo $selected."</br>";
        }
        //code for moving files goes here
        echo 'Files are moved!';
    }
  }
}

if($_POST['copy']) {
  if(isset($_POST['check_list'])){//to run PHP script on submit
    if(!empty($_POST['check_list'])){
    // Loop to store and display values of individual checked checkbox.
        foreach($_POST['check_list'] as $selected){
        echo $selected."</br>";
        }
        // code for copy goes here
        echo 'Files are copied!';
    }
  }
}

By submitting, php does not handle the data. What i am doing wrong? Can someone help me with that?

All the code is in the same file, called index.php




Aucun commentaire:

Enregistrer un commentaire