0

I trying to get data from php array and put in java-script variable. Follwoing are the php arrays.

Array Name

Array
(
    [0] => username
    [1] => byusers
)

Array Value

Array
(
    [0] => user
    [1] => 1
)

What I have Try tried

Get php array value in javascript variable

var DATATABLE_SEARCH_NAMES      = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_NAMES)) ? $DATATABLE_SEARCH_DATA_NAMES['names'] : 0;?>");
var DATATABLE_SEARCH_VALUES     = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_VALUE)) ? $DATATABLE_SEARCH_DATA_VALUE['values'] : 0;?>");
3
  • @u_mulder how can use it...? Commented Aug 26, 2014 at 10:55
  • If you're developing a web service, then this server response will automatically appear as an 'object' using javascript. then you can use it like this: username.user Commented Aug 26, 2014 at 10:56
  • json_decode( $arrayToDecode ); # converts arrays to JSON. Commented Aug 26, 2014 at 11:01

2 Answers 2

1

This should do what you ask, it is just a case of converting the PHP arrays to a form that javascript can understand. You can use json_encode() to do that.

$DATATABLE_SEARCH_DATA_NAMES = array('username','byusers');
$DATATABLE_SEARCH_DATA_VALUE = array('user', 1);

$js1 = json_encode($DATATABLE_SEARCH_DATA_NAMES);
$js2 = json_encode($DATATABLE_SEARCH_DATA_VALUE);

//echo $js1.PHP_EOL;
//echo $js2.PHP_EOL;

echo "<script>\n";
echo 'var names = ' . $js1 . ";\n";
echo 'var values = ' . $js2 . ";\n";
echo "</script>\n";
Sign up to request clarification or add additional context in comments.

Comments

1

say, you have a PHP array as this:

$arr = array("key1"=>"foo","key2"=>"bar");

the easiest way to put it to javascript is this:

var arr = <?php echo json_encode($arr); ?>;

ending with a JSON object.

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.