Home » Php » javascript – How to use AJAX to pass arrays to PHP?

javascript – How to use AJAX to pass arrays to PHP?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an array (selected), which stores the values of the checkboxes ticked. I created and populated this array using javascript. However, when using AJAX to pass this array to my PHP page, I get an error (Undefined index: kvcArray).
I know the array is not empty, as I have used the alert function to ensure it is populated.
Any advice on how to fix this?
I will attach my HTML/JavaScript code alongside the PHP code.

function getInterests() {

  var selected = new Array();

  var contentfilms = document.getElementById("content");
  var chks = contentfilms.getElementsByTagName("INPUT");

  // Loop and push the checked CheckBox value in Array.
  for (var i = 0; i < chks.length; i++) {
    if (chks[i].checked) {
      selected.push(chks[i].value);
    }
  }

  alert(selected);
  var myJSONText = JSON.stringify(selected);
  alert(myJSONText);
  $.ajax({
    type: "POST",
    url: "./test2.php",
    dataType: 'json',
    data: {
      'kvcArray': myJSONText
    },
    success: function() {
      alert("Success");
    }
  });

}
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link href="carousel.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
  <script type="text/javascript" src="ajax.js"></script>
</head>
<script type="text/javascript">
</script>


// PHP RETRIVAL CODE
<?php
$myArray = $_POST['kvcArray'];
print_r($myArray);
?>
How to&Answers:

you must use json_decode() to change from string to array in php

 <?php
 $myArray = json_decode($_POST['kvcArray']);
 print_r($myArray);
 ?>