0

I'm trying to store an array in the value of an element, and then use ajax to print the array, but when I tried to print the array, using print_r(), instead of printing the array, it printed the word array. What am I doing wrong?

<?php

$array[0] = 0;
$array[1] = 1;
$array[2] = 2;

echo "<input id = 'array' type = 'hidden' value = '$array'>";
//more codes

?>

In JavaScript:

var array = $("#"+array).val();
//more codes
data: { array: array },

On Second Page

array = $_POST['array'];
print_r(array);

Result

array

Expected Result

0
1
2
3
  • 2
    var array = $("#"+array).val(); ==> var array = $("#array").val(); Commented Jan 12, 2016 at 3:08
  • you can use json_encode while outputting the value on the input field and on next page before using the value use json_decode. You can also use serialize and unserialize to achieve the same effect Commented Jan 12, 2016 at 3:13
  • 1
    Why are you doing this anyway? PHP session variables may be a better way if you're just passing data between pages. Commented Jan 12, 2016 at 3:26

2 Answers 2

2

Convert your array to json before using it on JavaScript

echo "<input id = 'array' type = 'hidden' value = '" . json_encode($array) . "'>";

And decode it on the second page:

$array = json_decode($_POST['array']);
print_r(array);
Sign up to request clarification or add additional context in comments.

Comments

0

javascript and php have different syntax to use with array.

you should use

echo "<input id = 'array' type = 'hidden' value = '". implode(',', $array) ."'>";

...

On Second Page

$array = $_POST['array']; array = explode(',', $array); print_r(array);

Comments

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.