I want to plot graph using flot and mysql but an exception occurs
getData.php
$sql = mysql_query("SELECT count(Msg_ID) as msgCount,From_user
FROM Messages
GROUP BY From_user");
echo "[";
while($result = mysql_fetch_array($sql))
{
//print_r($result);
echo "[".$result['msgCount'].",".$result['From_user']."]"."\n";
}
echo "]";
And for plotting
<div id="plotarea" style="width:600px;height:300px;">
<script type="text/javascript">
var options = {
lines: { show: true },
points: { show: true },
xaxis: { min:0,max:5 },
yaxis: { min:1 ,max:60},
};
$.ajax({
url:"getData.php",
type:"post",
success:function(data)
{
alert(data);
$.plot($("#plotarea"),data,options);
//alert(data);
}
})
</script>
</div>
What is wrong with this code? Next I want to plot graph with one of the axis is time.
What you're trying to output is a json document in the php side, which will directly be parsed to a java script array (either manually or automatically by libraries like jquery)
So there is no need to print json in php instead you can easily feed data into a php array and use the json_encode function to easily convert it to a json string.
A small example could help you were trying to output
which in java script [] = array and you are creating [[]] = array inside array. But when the array is big, it's cumbersome to echo in php. What do we do. An array structure is similar in php. You will need to add data into php as an "array inside array" eg: php array(array(1,2,3)) = [[1,2,3]]. How to map it to json?
Cheers
Firstly it looks like the JavaScript list you are creating with your PHP code isn't separating each data point list item with a comma separator.
According to the jQuery $.ajax documentation the first argument passed to the
success
function is the data returned from the server, formatted according to the 'dataType' parameter. You haven't provided adataType
parameter. The docs say it will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response if nodataType
has been specified.I'm guessing the data getting passed to the plot function is a plain old string instead of a JavaScript list object as expected by Flot. Adding a
dataType: 'json'
option to your$.ajax
call should fix this up.The above will eliminate issues with comma separation (which, from what I can tell, you never resolved).
Next, the javascript:
Notice that I changed
$.ajax
to$.get
, since you weren't passing any data from the page to the script, a post is not necessary. And if you use$.get
, all of the setting names are assumed.Also notice that I pulled the script out of the html and put it within the jquery
window.onload
syntax :$(function () {
. This would go in the head of your html.From what I can tell, you aren't really in need of ajax, since you didn't define any sort of event that would trigger the $.ajax function. It looks like you are using ajax to call a script when you could just put the script into the same script that loads the page, like: