Reduan Kurtaj Reduan Kurtaj - 4 months ago 19x
jQuery Question

How can i sent an array with JS and AJAX

I have multiple input fields where a user can fill in answers to the question, with JavaScript i put the user input into a array.

When I view the console log inside google chrome I see the array wil be made correct, after that I want to sent the array with AJAX to a another php page so that i can save the data into my database.

When i check my database the post result = "Array" :(

someone who can help me???

////// JavaScript and AJAX code :

if (isConfirm) {
type: 'post',
url: 'actions/save_questions.php',
data: {'answers': allAnswers}

/////// PHP code :


$user_answer = $_POST['answers'];
$date = date('d-m-Y h:i:s');

$arr = array($user_answer);

$query = "INSERT INTO made_questions (lesson_id, user_answer, datum) VALUES ('1', '$arr', '$date')";
mysqli_query($conn,$query) or die (mysqli_error($conn));


The output into my database is:

id: 27

lesson_id: 1

user_answer: Array <----- this is wrong :(

datum: 16-06-2016 08:12:32

Console log output:

["horse", "nocleu", "Geel", "This is my dog", "Guten tag", "Sun", "Aap", "Honger", "knol", "Cat"]

Someone who maybe can help me???

Thanks a lot!


.toString() and .join() do not modify the original variable. You need to either say:

allAnswers = allAnswers.toString();


data: {'answers': allAnswers.toString()}


If you want the values ", " separated rather than just "," which is what is returned by .toString() you can say:

allAnswers = allAnswers.join(", ");


data: {answers: allAnswers.join(", ");