简体   繁体   中英

How to pass PHP array values to another file using jQuery Ajax?

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.

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] } ;

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