How to pass php array to javascript

Asked

Viewed 2,698 times

-2

I’m having trouble passing the $json[] array to Javascript, could someone help me.

<?php
    include_once ('../conf/conexaoBanco.php');
    $mensagem = "";

    $stmt=$conectarBanco->prepare("SELECT * FROM orcamento");
   $stmt->execute();
   **$json = [];
   while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
       extract($row);
       $json[] = (int)$quantidade;
   }**

?>

            <div class="container">
                <div class="row">
                    <div class="col-sm-6">
                    <h2 class="sub-orcamento">Orçamento Mensal</h2>

                    <canvas class="line-chart"></canvas>

                    <!-- Chartjs -->

                    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

                    <script>
                        var ctx = document.getElementsByClassName("line-chart");

                        //Type, Data e options
                        var chartGraph = new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: ["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],
                            datasets: [{
                                label:"Orçados de <?php echo date('Y') ?>",
                                **data: {"<?php $quantidade ?>"},**
                                borderWidth: 6,
                                borderColor: 'rgba(77,166,253,0.8)'
                            }]

                            }
                        })    

                    </script>
  • 1

    And why do you need to pass a PHP array to JSON? Are you familiar with the concepts of Client-Side and Server-Side? Could [Dit] your question and elaborate a [mcve]?

  • Anderson Carlos Woss I need to pass this array to Javascript in order to generate a Chartsjs chart based on my database information. Yes I know the Client-Side and Server-Side concept, but if you have any better suggestions feel free to inform me because I’m here to learn

  • Bruno, you say you have a problem passing a PHP array to JS, but you haven’t explained what the problem is. You just said you’re in trouble and put in a code. This doesn’t help much in getting a solution, because you don’t know what the problem is or the purpose of it.

  • Sam the problem I’m having is that I don’t know how to pass the $json[] array to the date attribute of Chatsjs and I’ve tried it several ways searching the internet only that none gives me a solution that I can buy how to do this procedure

4 answers

1

Sending Php Json to Javascript can make things easier, especially when working with Base64 files using Jsonurl, since PHP functions do not support this and strings need to be normalized (https://base64.guru/developers/php/examples/base64url). To facilitate, one of the solutions can be convert as follows:

$arrayJson = array(
  "nome"  => "joao",
  "idade" => 35
);

//codificar para Json (isso será passado para o Javascript)
$json = json_encode($arrayJson);

In Javascript you will receive this value normally (passing a Php variable to Js):

  <script>
  var jsonJS = <?=$json?>;
  //isso é um objeto json, então para acessar os valores trate ele como objeto:
  alert('nome: ' + jsonJS.nome);
  </script>

1


Here’s an example based on the content you reported:

<?php
$quantidade = [10, 15, 8, 5, 6, 9, 10, 7, 8, 11, 4, 5];
?>
<div class="container">
	<div class="row">
		<div class="col-sm-6">
		<h2 class="sub-orcamento">Orçamento Mensal</h2>

		<canvas class="line-chart"></canvas>

		<!-- Chartjs -->

		<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

		<script>
			var ctx = document.getElementsByClassName("line-chart");

			//Type, Data e options
			var chartGraph = new Chart(ctx, {
				type: 'line',
				data: {
					labels: ["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],
				datasets: [{
					label:"Orçados de <?php echo date('Y') ?>",
					data: <?php echo json_encode($quantidade) ?>,
					borderWidth: 6,
					borderColor: 'rgba(77,166,253,0.8)'
				}]

				}
			})    

		</script>

0

Use the function json_encode to convert a PHP value into a JSON representation.

It can be any PHP value, except Resource.

$json = [];
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $json[] = (int) $quantidade;
}

$json = json_encode($json);

In your javascript code, just print the variable $json which is already in JSON format.

data: <?php echo $json ?>,

-1

Transform array and JSON using json_encode. In javascript get this JSON

const MyArrayJS= (<?php echo json_encode($myArrayPHP)?>);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.