2

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.

2
  • sample.php just contains <?php $answers = Array ( [0] => 13 [1] => 5 [2] => 6 [3] => 11 ); ?> ? Commented Jan 24, 2013 at 10:01
  • 1
    have a look at turning your array into a JSON string. Commented Jan 24, 2013 at 10:03

1 Answer 1

7

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] } ;
Sign up to request clarification or add additional context in comments.

3 Comments

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 jQuery will build the string ans[]=13&ans[]=5&... which PHP will parse correctly as $_POST["ans"]=array(13,5,...);
@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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.