1

I have index.php file where i have a php array like this,

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);

and i want the $arr value in jquery function which is in another file named fetchvalue.js,

$(function  ()  {
    $('#barchart').sparkline(ARRAYFROMPHP, {
        type: 'bar', 
        barColor: '#3B5998',    
        height:'35px',
        weight:'96px'
    });
});

Please help me out in this. I am new to php and JS.Thanks in advance.

annemartijn
  • 1,538
  • 1
  • 23
  • 45
user1071321
  • 61
  • 2
  • 10
  • What does `.sparkline` do? – Pattle Mar 04 '14 at 11:05
  • You'll have to print the array, so you van use it in javascript. Take a look at this answer: [How to use an array value from php to javascript?](http://stackoverflow.com/a/2180190/1608705) – annemartijn Mar 04 '14 at 11:06
  • possible duplicate of [How to use an array value from php to javascript?](http://stackoverflow.com/questions/2180133/how-to-use-an-array-value-from-php-to-javascript) – annemartijn Mar 04 '14 at 11:09
  • 1
    @pattle .sparkline is piechart where the values in the array is used to draw them. – user1071321 Mar 04 '14 at 11:11
  • @annemartijn the link you shared is for php and JS in same where i have asked for php and js in different files. thanks – user1071321 Mar 04 '14 at 11:12
  • A more specific duplicate would be: http://stackoverflow.com/a/2928844/1608705 – annemartijn Mar 04 '14 at 12:06

5 Answers5

2

As you use jquery library , you can use $.getJSON() ( or $.ajax , or other method)

var ARRAYFROMPHP = [];
$.getJSON('index.php', function(data){
 ARRAYFROMPHP = data;
});
Aditya
  • 4,453
  • 3
  • 28
  • 39
Asenar
  • 6,732
  • 3
  • 36
  • 49
1

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.

Robin Webdev
  • 479
  • 2
  • 7
1

Call your url that gives you the json array and then trigger sparklines like this..

$(function  ()  {
    $.getJSON('your_url_for_json',{},function(response) 
    {           
        $('#barchart').sparkline(response, {
                type: 'bar', 
               barColor: '#3B5998',    
               height:'35px',
               weight:'96px'
           });  

    }); 
});
Aditya
  • 4,453
  • 3
  • 28
  • 39
0

You can use JSON string directly in js:

console.log(ARRAYFROMPHP['a']);
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

Php is server side language while JS is client side. You cannot make talk to each other directly. Use some sort of web service or Ajax to interact.

$.ajax({
url: 'Call URL',
type: "GET",
dataType: "json",
success: function (data) {
    //Date will be your JSON returned from the PHP.
    alert(data)
}
});
Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56