Reputation: 75
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.
Upvotes: 1
Views: 4407
Reputation: 7010
As you use jquery library , you can use $.getJSON()
( or $.ajax , or other method)
var ARRAYFROMPHP = [];
$.getJSON('index.php', function(data){
ARRAYFROMPHP = data;
});
Upvotes: 2
Reputation: 4463
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'
});
});
});
Upvotes: 1
Reputation: 3101
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)
}
});
Upvotes: 0
Reputation: 479
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.
Upvotes: 1
Reputation: 43481
You can use JSON string directly in js:
console.log(ARRAYFROMPHP['a']);
Upvotes: 0