简体   繁体   中英

send php array through jquery ajax with index and recieve the array value

i am working on online exam test where childArray[] contains data from each row of table and parrentArray[] contains number of childArray[]. i want to get value of each childArray from ParentArray with Index passed through ajax.

<?php 
 $childArray1[]=[1,question,optionA,optionB,optionC];
 $childArray2[]=[1,question,optionA,optionB,optionC];
 $parentArray[]=[$childArray1,$childArray2];
?>

<script>
$(document).ready(function(){
    var counter=0;
    $("#ButtonNext").click(function(){
       $.ajax({
           type:"POST",
           url: "ChangeQuestionProcess.php",
           data:{
               MainList:"<?php echo json_encode($parentArray); ?>",
               Counter:counter,
           }, 
           success: function(result){
            $("#callMe").html(result);
        }});
        counter++;
     });
   });
</script>

ChangeQuestionProcess.php

<?php
  $index=$_POST["Counter"]; 
  $test[]=$_POST["MainList"];
  echo test[$index];
?>

In your ChangeQuestionProcess.php , this line:

$test[]=$_POST["MainList"];

...is saying "take the contents of $_POST["MainList"] and make it the next element of the array $test "

You're doing a similar thing at the top of your first script - I think you mean this, without the [] after the variable names:

<?php  
  $childArray1=[1,'Question 1','Option 1A','option 1B','option 1C'];
  $childArray2=[2,'Question 2','Option 2A','option 2B','option 2C'];
  $parentArray=[$childArray1,$childArray2];
?>

You could even simplify this to:

<?php
  $parentArray = [
    [1,'Question 1','Option 1A','option 1B','option 1C'],
    [2,'Question 2','Option 2A','option 2B','option 2C']
  ];
?>

Now back to ChangeQuestionProcess.php again - bear in mind that $_POST["MainList"] is going to be a string containing JSON-encoded data (as that's what json_encode() returns)

Therefore what I think you are trying to do is read the array of JSON- decoded data into $test , which you would do like so:

$test = json_decode( $_POST["MainList"] );

Finally, you're missing a $ when echoing your variable. But as $test[$index] is an array, you'll just see Array on your screen instead of its contents. I think you need something like print_r instead of echo :

<?php
  $index = $_POST["Counter"]; 
  $test = json_decode( $_POST["MainList"] );
  print_r( $test[$index] );
?>

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