I've an array in my php called as $tempoHeader
, for example:
-------
Array
(
[0] => red
[1] => green
[2] => yellow
[3] => blue
)
I want to send it into my external javascript, so I do this one in my php code:
$tempoHeader = array_diff_assoc($modelData, $data);
<script type="text/javascript">var header = <?php echo json_encode($tempoHeader); ?>;</script>
<script type="text/javascript" src="upload_header.js"></script>
In my javascript, I've try to console.log(header);
and I got this in my console
Array [ "red", "green", "yellow", "blue" ]
$(window).load(function() {
console.log(header); //this work and print out the header json
var myObject = JSON.parse(header);
var myArray = jQuery.parseJSON(header);
console.log(myArray); //didn't print out anything
console.log(myObject); //didn't print out anything
});
Note: I've read this issue jQuery JSON Decode ( PHP to Javascript), and I've try the suggestion such as jQuery.parseJSON(header);
, JSON.parse(header);
but I got nothing
$res = json_decode( $tempoHeader, true );
echo $res->array_name[index];
I hope this help
header
already is an array, it is not json / a string and you do not need to parse it.
You send this to javascript:
var header = <?php echo json_encode($tempoHeader); ?>;
So you already have an array in javascript as you have noticed:
Array [ "red", "green", "yellow", "blue" ]
And then you try to parse that as json:
var myObject = JSON.parse(header);
That is not possible nor is it necessary: json is a string and JSON.parse()
expects a string as its parameter. You cannot use it on an array.
To use your variable, you can simply use header[0]
(red), etc. or loop over it like you do with any other javascript array.
The Problem here is that when you executes your JavaScript, your PHP Script was already executed, to "send a variable back to php" you have to create a new Request.
Mostly it is done via Ajax OR you can add your Array in a hidden input field and "send" it with a form.
So you upload_header.js would look like
$(function () {
$.ajax('update_header.php', {
method: 'POST',
data: {
'header': JSON.stringify(header)
}
})
});
and in your "update_header.php" you would recieve the new header with
$newHeader = json_decode($_POST['header'],true);
hope this helps;)