1

I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:

$shelvDate = $_POST['shelvDate'];
$x = 0;

// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
    WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;

if($num_rows > 0){
    while($row = $shelv->fetch_assoc()) {
        if($row['qty'] > 0){
            $qtyArray[$x] = $row['qty'];
            $nameArray[$x] = $row['first_name'];
        }
        $x++;

        $pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
    } // end of while statement
} //end of if statement

$conn->close();
echo json_encode(array($pairs));

When I attempt to get the data into my ajax/js I get an error. My JS is:

$("#getRecords").live('click', function() {
    var ajaxDataRenderer = function(url, plot, options) {
        var ret = null;
        $.ajax({
            type: "POST",
            async: false,
            url: url,
            dataType:"json",
            data: ({shelvDate: $('#shelvDate').val()}),
            success: function(data) {
                for(var x=0; x<data.first_name.length; x++) {
                    var info = [data.first_name[x], data.qty[x]];
                    ret.push(info);
                }
        }); // end of ajax call

        return ret;
    }; // end of ajaxDataRenerer call

    // The url for our json data
    var jsonurl = "shelvChart.php";
    var plot2 = $.jqplot('shelvChart', jsonurl,{
    seriesDefaults: {
           // Make this a pie chart.
           renderer: jQuery.jqplot.PieRenderer,
           rendererOptions: {
               // Put data labels on the pie slices.
               // By default, labels show the percentage of the slice.
               showDataLabels: true
           }
        }, 
        title: "Books Shelved",
        dataRenderer: ajaxDataRenderer,
        dataRendererOptions: {
            unusedOptionalUrl: jsonurl
        }
    });
});

I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim

Emil Sierżęga
  • 1,785
  • 2
  • 31
  • 38
Jim
  • 1,315
  • 4
  • 17
  • 45
  • What is the result of `console.log(data);` inside of `success: function(data) {}` – c.hill May 22 '12 at 14:45
  • if I add in an alert box in the success:function(data), I get name[object,object],qty[object,object]. – Jim May 22 '12 at 15:57

1 Answers1

1

It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.

Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.

Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:

ret = [[name[0], qty[0]], [name[1], qty[1]], ...]; 

This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.

Similar approach that shows how to prepare data for a chart is shown in this answer.

Community
  • 1
  • 1
Boro
  • 7,913
  • 4
  • 43
  • 85
  • After doing some debugging, I was able to get some actual data out of my mysql query. Now in the alert(ret) I get: first_name,Mike,Cory,Doug,Pond,Santos,qty,471,80,101,59,46. I though json was supposed to format this info in [ ] form. I will look at your example now and see if it makes any sense to me. Thanks for the help. – Jim May 23 '12 at 12:33
  • I used your code example parts of your code example and now get my alert formatted as : mike,471, cory,80 etc.. but I still do not get it plotted on my chart. any suggestions? – Jim May 23 '12 at 13:40
  • Please provide jsfiddle that shows your problem. I am not really sure what is the problem there without seeing the actual code. Also my suggestion was to have arrays of consisting of a [name, qty] pair in `ret` array. – Boro May 23 '12 at 14:23
  • I was able to get the ret array as [name, qty], now I just can't get the information to show on my chart. I will attempt to get it in jsfiddle now. Thanks – Jim May 23 '12 at 14:50
  • The example code you provided is not runnable, therefore, I cannot see what your problem is. Please, copy and past the **exact** output you are getting when you call `console.log(ret)` or `alert(ret)` after a call to `ajaxDataRenderer` or the result of what you do in your code `alert(JSON.stringify(ret));`. Try just calling the method and outputting the returned value. – Boro May 23 '12 at 15:20
  • [["Mike", "471"], ["Cory", "80"], ["Doug", "101"], ["Pond", "59"], ["Santos", "46"]] is the result of console.log(ret) after calling ajaxDataRenderer. Thanks for all of your help. – Jim May 23 '12 at 15:26
  • At the first look the problem is that you are giving Strings as the second element in each arrays and the plot expects values. This jsfiddle shows a pie chart done for your data with consideration that the 2nd element is not a String http://jsfiddle.net/v8Kkh/3/ – Boro May 23 '12 at 15:46
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/11654/discussion-between-jim-and-boro) – Jim May 23 '12 at 17:05