Best Way to Transfer an Array Between PHP and JavaScript

Best way to transfer an array between PHP and Javascript

I tend to use a JSON object for this:

  • On the server side, JSON encode your data: json_encode($data);
  • On the JavaScript side, I write a function that takes a JSON object as a parameter and unpack it.

When you unpack the object, you can print the array's contents into a <DIV> tag, or where ever you would like on the page (jQuery does a pretty sweet job of this).

Pass a PHP array to a JavaScript function

In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:

<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);

<!-- Then pass it to the JavaScript function: -->

drawChart(<?php echo count($day); ?>, day, week, month);
</script>

Pass Javascript Array - PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

Best way to pass a 2d array into JavaScript from PHP?

As a JSON Object using the json_encode function. You can then read this with Javascript easily as it is a native javascript object. http://php.net/manual/en/function.json-encode.php

json_encode($array);

JSON is easily parsable in JQuery, but for pure JavaScript see here:

http://www.json.org/js.html

How to pass php array to another js file

You have to pass your PHP array to JS.

echo '<script>var arrayFromPhp = ' . json_encode($arr) . ';</script>';

after that you can access the array in your JS file in the variable arrayFromPhp.

Not that JS doesnt have associative arrays so your example would be an object.

how to move array from javascript to php and print it

Since you need to send the values as a string (this is required due to the underlying protocol), you need to encode them. One of the standard ways to do this is to use JSON. So at the client side:

var array = ['some', 'array'];
// send it to the client via XHR
var xhr = new XMLHttpRequest();
xhr.open('POST', '/path/to/backend/reciever.php');
var fd = new FormData();
fd.append('data', JSON.stringify(array)); // stringify as JSON
xhr.send(fd); // send the complete data
xhr.onload = function () {
console.log(xhr.responseText);
};

Then on the backend:

$recieved = $_POST['data']; // get recieved json encoded data
$decoded = json_decode($recieved); // decode it back to an array
echo $decoded[0]; // echo the first element

What we are doing above is basically encoding the data as JSON and then sending it to the backend. Then decoding it back on backend and echoing out what we need.

Hope that helps.

Passing PHP array to Javascript w/o showing up in source

There are in principle two ways you can think of to get data in JavaScript:

1. Ajax request

With this solution use your current PHP file for generating the HTML page only, so without generating JSON, and create another PHP file which will generate the JSON only.

So let's say your JSON-generating PHP file is called fhs_get_photos.php, then it would have this code (no HTML!):

<?php
header("Content-Type: application/json");

// Collect what you need in the $result variable.
// ...
// and then:

echo json_encode($result);

?>

See the last section in my answer for treating JSON encoding errors.

Make sure there are no line breaks or spaces before the opening <?php, and that you do not echo or print anything else than that one JSON string.

Your database query would also be in this new file. Note that currently you have a mix, like with this line:

echo "<img src = "."'".$filename."'" ."/>";

This line belongs in the non-JSON file, but it also depends on the query. So either you make an include file that does the query, include it in both PHP files, or you move the logic of defining the image tag (or at least the image's source) to the JavaScript part (better!).

Then in the original PHP file, remove the JSON output, and add some JavaScript, using jQuery (I understood you were already using it, so you have it included):

$(function(){
$.getJSON("fhs_get_photos.php", function(photo_array){
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
$.each(photo_array, function(i, obj){
$("#dom-target").append(obj['fhs_pkey'] + " " + obj['file_name'] + ", ");
});
// or things like:
$("#caption_input").val(photo_array[2]['caption']);
});
});

This function will get executed once the HTML DOM has been built, so evidently after the first PHP file has finished execution. It will make the request to the second PHP file. Once that request is answered by PHP, the inner call-back function will receive the data. Note that there is no need to decode JSON here, as jQuery has already done that for you.

2. Generate JavaScript with data

Here you keep your current PHP file, but move the part where you inject the JSON encoded data to the JavaScript block:

    <script>
var photo_array = <?php echo json_encode($result); ?>;
// ... process it
</script>

There is no need to wrap JSON in a JavaScript string to then parse it.

From json.org:

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

2.1. Valid JSON that could be invalid JavaScript?

Although not a problem in the context of this question (see below), there is an incompatibility between JSON and JavaScript syntax. It concerns whether or not the non-ASCII characters U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed to appear unescaped in quoted strings:

  • JSON syntax allows this, as stated in the ECMAScript® 2015 Language Specification, section 24.3.1:

    JSON allows Unicode code points U+2028 and U+2029 to directly appear in String literals without using an escape sequence.

  • JavaScript syntax does not allow this, as indicated in the ECMAScript® 2015 Language Specification, section 11.8.4:

    All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence.

PHP's json_encode however, follows the possibility offered in that last line, and escapes all non-ASCII characters, including the problematic U+2028 and U+2028, except if you explicitly tell PHP not to do so with the JSON_UNESCAPED_UNICODE flag:

JSON_UNESCAPED_UNICODE (integer)

  • Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.

So, a json_encode call without this flag will not produce instances of this problem.

3. Catch json_encode failures

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($result) will output the empty string, which is invalid JSON.

This error condition should be captured in PHP, for example like this:

<?php
header("Content-Type: application/json");

// Collect what you need in the $result variable.
// ...
// and then:

$json = json_encode($result);
if ($json === false) {
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
}
?>

And then in JavaScript, this condition should be handled as well, for example like this:

if (photo_array.jsonError !== undefined) {
alert('An error occurred: ' + photo_array.jsonError);
return;
}

Best method for converting a PHP array to javascript

Use JSON. see why JSON over XML: http://thephpcode.blogspot.com/2008/08/why-json-over-xml-in-ajax.html

To use json in PHP simply:

<?php

echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var train = '.json_encode($array);
echo '/* ]]> */</script>';

?>

the variable train in Javascript will be an object containing properties and arrays based on your PHP variable $array.

To parse or iterate through the train object, you can use for ... in statements for JSON arrays, and directly use object.property for JSON objects.

See this:

<?php

$array = array(array('id'=>3,'title'=>'Great2'),array('id'=>5,'title'=>'Great'),array('id'=>1,'title'=>'Great3'))
echo '<script type="text/javascript">/* <![CDATA[ */';
echo 'var train = '.json_encode($array);
echo '/* ]]> */</script>';

?>

The output will be:

 var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];

the variable train becomes an array of objects. [] squrare brackets are arrays, holding more arrays or objects. {} curly braces are objects, they have properties to them.

So to iterate the train variable:

<script type="text/javascript">

var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];

for(i in train){
var t = train[i]; // get the current element of the Array
alert(t.id); // gets the ID
alert(t.title); // gets the title
}

</script>

Simple! Hope that really helps.



Related Topics



Leave a reply



Submit