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.

6
  • What does .sparkline do? Commented Mar 4, 2014 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? Commented Mar 4, 2014 at 11:06
  • possible duplicate of How to use an array value from php to javascript? Commented Mar 4, 2014 at 11:09
  • 1
    @pattle .sparkline is piechart where the values in the array is used to draw them. Commented Mar 4, 2014 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 Commented Mar 4, 2014 at 11:12

5 Answers 5

2

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

var ARRAYFROMPHP = [];
$.getJSON('index.php', function(data){
 ARRAYFROMPHP = data;
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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'
           });  

    }); 
});

Comments

0

You can use JSON string directly in js:

console.log(ARRAYFROMPHP['a']);

1 Comment

Thanks for the reply can you please explain me in little detail how to achieve it.
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)
}
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.