L
L
limpopo19922015-04-12 15:49:12
PHP
limpopo1992, 2015-04-12 15:49:12

How to pass array from php to javascript?

Hello!
How to pass php array to javascript?
In the php code we have:

$kolz5 = mysql_query("SELECT * FROM numbers") or die ("error: ".mysql_errno());
$content = array(); 
while (($row=mysql_fetch_assoc($kolz5)) !== false) { # запись запроса в массив
                        $content[] = $row ; }

in the javascript code we accept:
alert(data);
Tried with json_encode, but in this way, because there is text in the array, gibberish like u is passed instead... and so on.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton Dyshkant, 2015-04-12
@limpopo1992

PHP:

$content = array('абвгд', 'abcdefg', '12345'); 
echo json_encode($content);

JS (+jQuery):
If for some reason abracadabra is displayed, then the problem is definitely not in JSON, but in the encoding.
That is, there must be a match between the encoding of the field in the table and the encoding of the html document (for example, UTF-8):
<html>
  <head>
    <meta charset="utf-8">
  </head>
  ...
</html>

In this case, the database should have:
Collation: utf8_general_ci

F
FanatPHP, 2015-04-12
@FanatPHP

abracadabra like u...etc.

and what? what does she do to you?

M
Mikhail Osher, 2015-04-12
@miraage

// php 5.4+
json_encode($content, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);

V
Vahe, 2015-04-12
@vahe_2000

<script type="text/javascript">
var ar = <?php echo json_encode($ar) ?>;
</script>

The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it as we demonstrate here with a numerically indexed array:
<script type="text/javascript">
var fruits = <?php echo '["' . implode('", "', $fruits) . '"]' ?>;
</script>

The implode() function returns a string from the elements of an array.
The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.
The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.
This function is binary-safe.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question