Return json to a variable

Asked

Viewed 875 times

0

I have a code in PHP that creates a json:

<?php

$array3 = array(array('0,1300', 'Thalita', 'Nicole'));


echo json_encode($array3);
?>

And I have another code that is in jQuery that forms a graph, with the following settings:

var d1 = [
        [0, 1450], [1, 1300], [2, 1600], [3, 1900], [4, 2100], [5, 2500], [6, 2200], [7, 2000], [8, 1950], [9, 1900], [10, 2000], [11, 2120]
    ];

I need to do is take the return of the json I created with PHP and play in this variable D1 to form the graph correctly. And not forgetting that you have to return with two [[ ]] as the variable D1 above.

  • How do you want to process the PHP return? It would be through a method?

  • I would like to take the return of PHP, can be for $.post, $.ajax and play the result and play in the variable jQuery. I need to form a variable equal to D1.

  • @Alissonacioli, the two arrays are different. One has two fields per array, the other 3 and not numerical. What graph are you using? Flot? Highcharts?

  • Just remembering that in the latest versions of PHP you can declare arrays in a very similar way to Javascript. The first array with names you created would be: $array3 = [['0,1300', 'Thalita', 'Nicole']]; Now to create the array you want: $array = [[0 => 1450, 1=>1300, 2=>1600, 3=>1900]]; // etc

1 answer

1


If so, you can create this array in PHP as you are creating it, and send it through a function:

<?PHP
    $array3 = array(array('0,1300', 'Thalita', 'Nicole'));
    $jsonArr=json_encode($array3);
?>
<script>
    function makeGraph(data){
        d1=data;
        //manipulação de array dentro do javascript...
    }
</script>
<body onload="javascript:makeGraph(<?= $jsonArr ?>);">

The action onload no body was just to demonstrate the method call, you can put the code inside it in any script or HTML action.

  • But PHP is on one page and JS is on another. And variable D1 will have q stay out of Function, if not, does not play for chart variable

  • Can you put a little more of your jQuery and PHP code in your question? It’s a little hard to understand what the code should do.

  • I found a code on the internet here that even does what I want, only at the time of running the page to work, gives an error in Chrome, then I click Reload and same thing happens. But what I want is the following, to create a chart with jQuery + PHP, to take the graph data dynamically with PHP. You or someone would have one to indicate?

  • You have Highcharts, you can pass the data through AJAX or even PHP itself, putting PHP code in the script tag. There’s also Phpchart and jPChart. Links: https://www.google.com/search?client=ubuntu&channel=fs&q=PHP+charts&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=F-PCU4inDqOX8Qejp4H4Cg and http://www.highcharts.com/

Browser other questions tagged

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