How to pass PHP array values to another file using jQuery Ajax?
ajax, javascript, jquery, php
Solution
The line:
var dataToSend = {'name' : val, 'ans[]' : <?php echo $answers; ?> } ;
will print:
var dataToSend = {'name' : val, 'ans[]' : Array } ;
which creates a javascript syntax semantic error (ans = empty string will be posted). Change to:
var dataToSend = {'name' : val, 'ans[]' : <?php echo json_encode($answers); ?> } ;
which prints:
var dataToSend = {'name' : val, 'ans[]' : [13,5,6,11] } ;
Problem
Here is my code, ``` <?php $answers = Array( [0] => 13 [1] => 5 [2] => 6 [3] => 11 ); ?> <script> function loadData1(val) { var dataToSend = { 'name': val, 'ans[]': <? php echo $answers; ?> }; $.ajax({ type: 'POST', data: dataToSend, url: '<?php echo JURI::ROOT();?>classfiles/sample.php', success: function (data) { $('#questions').html(data); } }); } </script> ``` I want the array values in `sample.php` file, but I don't get any output. Any useful answers are really appreciated.