Home > Back-end >  sending array via ajax to php
sending array via ajax to php

Time:03-14

I want to send an array of ids for the checked checkboxes via ajax to PHP. I keep getting Undefined array key "progid". when I alert the progid in jQuery I got the correct ids. I know it is duplicated question but I really searched a lot and tried a lot of solutions nothing works.

html code:

 while($row3 = $result3->fetch_assoc()) {
     $courseName = $row3['courseName'];
     $coursePrice = $row3['coursePrice'];
     $courseId = $row3['id'];
     $programList .= ' <div >
                    
     <input type="checkbox" name="course[]"  id="'.$courseId.'" value="'.$coursePrice.'">
     <label  for="'.$coursePrice.'">'.$courseName .' price is '.$coursePrice.'$</label>
     </div>';

 } 
 echo $programList;

jQuery code:

$('#submit').click(function() {
    var progid = [];
    $.each($("input[name='course[]']:checked"), function(){
        progid.push($(this).attr("id"));  
    });  
                   
    $.ajax({
        type: "POST",
        url: "test.php",
        data: progid,
        success: function(data){
            console.log('success: '   progid);   
        }
    });  
});

php code:

<?php
  extract($_POST);
  print_r($_POST);
  echo ($_POST["progid"]);
?>

CodePudding user response:

Because you didn't post all the html, is it possible that your submit event is not disabled with event.preventDefault(); and the ajax is not executing?

$('#submit').click(function(e) {
    e.preventDefault();
..

https://api.jquery.com/event.preventdefault/

$.ajax({
        type: "POST",
        url: "test.php",
        data: {"progid" : progid},
        success: function(data) {
            console.log('success: '   progid);   
        }
    });

CodePudding user response:

You can use JSON.stringify() for the array:

$('#submit').click(function() {
    var progid = [];
    $.each($("input[name='course[]']:checked"), function(){
        progid.push($(this).attr("id"));  
    });
  
    let stringifyProgid = JSON.stringify(progid);
                   
    $.ajax({
        type: "POST",
        url: "test.php",
        data: {progid: stringifyProgid},
        success: function(data){
            console.log('success: '   progid);   
        }
    });  
});

And in PHP you can get the array:

<?php
  $arrProgid = json_decode($_POST["progid"]);
  var_dump($arrProgid);
?>
  • Related