简体   繁体   中英

checkbox jquery using ajax to send data and save in php not inserting

I tried to serialize rather to push the elements value but still I get the array with inserting each value 9 times in database. please anyone to help me figure out my problem this is what I am trying to

The HTML:

    <form name="chkl" id="chkl" method="post">  
                
<input type="checkbox" class="get_value" name="chk1[ ]" value="<?php echo $rows['ID'];?>">&nbsp<?php echo $rows['DESCRIPTION'];?></input><br>

<input type="submit" name="Submit" id="chk1" value="Submit"> 

JS:

<script>
 $('#chk1').click(function(){  
$('input[type=checkbox]').each( function() {
          $.post('fee_checked_save.php', $( ".get_value" ).serialize(), function(data){
          if(data == 1){
             $('#result').html(data);  
          }
      });
});
});
</script>

PHP:

<?php  
    
  $checkbox1 = $_POST['chk1'];
    if(isset($_POST['chk1']))  
    {  
    for ($i=0; $i<count ($checkbox1);$i++) {  
    $query = "INSERT INTO fee_checked(FEE_ID) VALUES ('".$checkbox1[$i]. "')";  
   $result = mysqli_query($conn, $query);
    }  
    echo "Record is inserted";  
    }  
    ?>  

Any help would be greatly appreciated. Thanks ahead of time!

You are sending all checkbox value but, i think you need to only send checkbox which is checked so use :checked then you have use $( ".get_value" ).serialize() this is targetting all class that's why you are seeing mutliple insert instead change that to $(this).serialize() . I have added other way as well instead of sending checkbox ony by one you can use $(this).closest("form").serialize() to send whole form datas at onces.

Demo Code :

 $('#chk1').click(function(e) { e.preventDefault() //send only input which is checked $('input[type=checkbox]:checked').each(function() { console.log($(this).serialize()) //use `this` here,, $.post('fee_checked_save.php', $(this).serialize(), function(data) { if (data == 1) { $('#result').html(data); } }); }); }); //prefer way: $('#chk1').click(function(e) { e.preventDefault() console.log("from second way.." + $(this).closest("form").serialize()) $.post('fee_checked_save.php', $(this).closest("form").serialize(), function(data) { //some codes }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form name="chkl" id="chkl" method="post"> <input type="checkbox" class="get_value" name="chk1[]" value="1">&nbsp; Soemthings.. <input type="checkbox" class="get_value" name="chk1[]" value="2">&nbsp; Soemthings.. <input type="submit" name="Submit" id="chk1" value="Submit"> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM