i have a code with the javascript and php jow can i seperate this loop data.
<script type="text/javascript" class="code">
$(document).ready(function(){
var line1 = [['<?php echo $row["name"]; ?>', <?php echo $row["number"]; ?>]];
$('#chart1').jqplot([line1], {
title:'The Socialhog Graphic Chart',
seriesDefaults:{
renderer:$.jqplot.BarRenderer
},
axes:{
xaxis:{
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
});
</script>
a better method to do this would be to have JS fetch json data from PHP script.You can use json_encode in php to encode your array into php and make an ajax call from the javascript to fetch the JSON result. This way your JS and PHP stay in separate files and the code is better manageable .
You can do it in various ways.
The vars.php file is accessible at http://localhost/vars.php
header('Content-type: application/json');
echo json_encode([['<?php echo $row["name"]; ?>', <?php echo $row["number"]; ?>]]);
The javascript file (or the inline script in your HTML)
function jqPlot(url) {
$.get(url, function(response) {
// uncomment this if you cannot set the header in PHP
// if(typeof response === 'string') response = JSON.parseJSON(response);
$('#chart1').jqplot([response], {
title:'The Socialhog Graphic Chart',
seriesDefaults:{
renderer:$.jqplot.BarRenderer
},
axes:{
xaxis:{
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
});
}
$(document).ready(function(){
makeJqplot('http://localhost/vars.php');
});
A PHP file on your server named jsvars.php
$javascriptVars = [
"line1": [[ $row["name"], $row["number"] ]],
// maybe other vars
];
header('Content-type: text/javascript');
echo "jsVars = " . json_encode($javascriptVars) . ";";
In your HTML
<script type="text/javascript" src="http://localhost/jsvars.php"></script>
<script type="text/javascript" class="code">
$(document).ready(function(){
$('#chart1').jqplot([jsVars.line1], {
title:'The Socialhog Graphic Chart',
seriesDefaults:{
renderer:$.jqplot.BarRenderer
},
axes:{
xaxis:{
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
});
</script>
I'm using jsVars just to namespace these variables. You will want to have them namespaced.
If the number of HTTP requests are an issue for you, there is another approach, but is more about looking more clearer. It's still dirty. Instead of directly outputting the php in your <script>
tag, you might want to make an invisible div (#invisiblediv
) and put there a JSON, then read that with
var line1 = JSON.parseJSON($('#invisiblediv').html());
Hope that helps.