I'm working on PHP and trying to pass a PHP array to a javascript code to create an attribute dynamically and set the values to it.
I've been sending the PHP array like below.
PHP Code
$dataArray = array();
array_push($dataArray, $ticket['tickets']);
array_push($dataArray, $pendingTicket['pending_tickets']);
array_push($dataArray, $closedTicket['closed_tickets']);
Following is the PHP array.
Array
(
[0] => 4
[1] => 3
[2] => 1
)
JS Code
<script type="text/javascript">
var jArray = <?php echo json_encode($dataArray); ?>;
var ticketGraphData = [];
for(var i=0; i<jArray.length; i++){
ticketGraphData.push(jArray[i]);
}
alert(typeof ticketGraphData);
console.log(ticketGraphData);
var anchor1 = document.getElementById("firstGraph");
var anchor2 = document.getElementById("secondGraph");
var att1 = document.createAttribute("data-values");
var att2 = document.createAttribute("data-values");
att1.value = ticketGraphData;
anchor1.setAttributeNode(att1);
att2.value = ticketGraphData;
anchor2.setAttributeNode(att2);
</script>
I want to make pass the ticketGraphData
values as [4,3,1]
.
But here when I tried to console the data and returned an alert, it is showing Object
in the alert and displayed the following data in the console.
After setting the data to the attribute
, it is looking like,
data-values="4,3,1"
But I want to make them as,
data-values="[4,3,1]"
Where am doing mistake? Is there any other alternative to achieve this?