Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
sample.php just contains <?php $answers = Array ( [0] => 13 [1] => 5 [2] => 6 [3] => 11 ); ?> ? – Chris Till Jan 24 at 10:01
1  
have a look at turning your array into a JSON string. – SubstanceD Jan 24 at 10:03

1 Answer

up vote 3 down vote accepted

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] } ;
share|improve this answer
Thanks @salman. I got it... – hmb Jan 24 at 10:03
suppose key like ans[] can make a problem. If I'm not missing something, PHP will parse that like Array([0] => Array([0] => 13...)), so simply ans should be enough – FAngel Jan 24 at 10:04
@FAngel jQuery will build the string ans[]=13&ans[]=5&... which PHP will parse correctly as $_POST["ans"]=array(13,5,...); – Salman A Jan 24 at 10:09
@SalmanA Ha! Cool! Sorry, I thought it will build ans[][]=13&ans[][]=5&... because array is being passed. But appears that in both cases (when key is ans or ans[]) it builds a string like ans[]=13&ans[]=5&... Will remember this... – FAngel Jan 24 at 10:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.