0

im trying to pass an javascript array variable into php file

I have arrayID variable with 5 values. What i did is i put the arrayID in this <input id="array" type="text" name="aID[]" value=""> tag with this javascript code document.getElementById("array").value = arrayID; because the input tag is inside this <form method="post" action="AddAssessment.php"> tag so that i can get the value of arrayID from AddAssessment.php

This is from AddAssessment.php file

<?php 

session_start();

require("connection.php");

if(isset($_POST['btnSubmit2']))
{
    $questionID=$_POST['aID'];

        for ($i=0; $i<count($questionID);$i++) 
        {
            $SqlQ_T = "INSERT INTO assessment_question_table (Question_ID) values ('$questionID[$i]');";
            mysqli_query($con,$SqlQ_T);
            print_r ($questionID);
        }
        echo "<script>alert('Assessment Added!');</script>";
    }
}?>

So whenever the btnSubmit2 is clicked it calls the input name using post and gets the value of the input which is the arrayID and put it in the $questionID variable. And then save the value of the array one by one in the database using loop as you can see above

The problem is it only save the first value of the array. So i tried to print_r the $questionID variable and i get this

Array ( [0] => 9,10,12,31,20,53 )

What is the proper way to pass javascript array to php file so i can count every index in the array and do the looping?

I'm new here so i hope my explanation is good if not just ask me don't give me down vote. Any help will be appreciated Thank you :)

asdf
  • 17
  • 5
  • Possible duplicate of [How to pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – Vural Sep 03 '17 at 11:54

1 Answers1

0

If you get , seperated value and you want to convert it nto array you can use explode function of PHP

$questionID=$_POST['aID'];
if(is_array($questionID) && isset($questionID[0]))
{
  $questionID = explode(",", $questionID[0]); // convert to array
}

        for ($i=0; $i<count($questionID);$i++) 
        {
            $SqlQ_T = "INSERT INTO assessment_question_table (Question_ID) values ('$questionID[$i]');";
            mysqli_query($con,$SqlQ_T);
            print_r ($questionID);
        }
        echo "<script>alert('Assessment Added!');</script>";
    }
Vural
  • 8,532
  • 11
  • 38
  • 55
B. Desai
  • 16,264
  • 5
  • 24
  • 44