0

I want to create a Google graph in Wordpress, using data that I collect from Google Datastore with a Wordpress plugin (i.e. with PHP). I have followed this, but getting the code to work in Wordpress requires a little more. I have a Javascript file, and a PHP file (the Wordpress plugin, where I want the graph to be displayed).

Javascript is working and Ajax works when sending data from Javascript to PHP, so I have at least made the necessary adjustments in Wordpress for this basic functionality. But I need to get the data from PHP to the Javascript functions for drawing the graph, which isn't working. (The Ajax error function gets called.)

javascript.js

createGraph();

function createGraph() {
    google.charts.load('current', {packages: ['corechart', 'line']});
    google.charts.setOnLoadCallback(drawGraph);
}

function drawGraph() {
    jQuery(document).ready(function($) {
    var jsonData = null;
    var json = jQuery.ajax({
        url: ajax_object.ajax_url,
        data: {
        'action': 'ajax_request'
        },
        dataType:"json",
        async: false,
        success:function(data) {
            console.log(data);
            jsonData = data;
            var data = new google.visualization.DataTable(jsonData);        

            // Instantiate and draw our chart, passing in some options.
            var options = {
                hAxis: {
                    title: 'Time',
                    logScale: true
                },
                vAxis: {
                    title: 'Popularity',
                    logScale: false
                },
                colors: ['#a52714', '#097138']
            };

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        },
        error: function(errorThrown){
            console.log(data);
        }
    });
    }).responseText;
}

plugin.php

...

// Getting jQuery/Javascript/Ajax to work
function my_enqueue() {
   // Only works on specific page
   if(is_page (151)) {
      wp_enqueue_script('javascript', plugins_url() . '/embed_cloud_datastore/js/javascript.js', array('jquery'), '1.0.0', true);

      // We can define the AJAX url with using wp_localize_script
      wp_localize_script( 'javascript', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
   }
}
add_action('wp_enqueue_scripts', 'my_enqueue');
add_action( 'wp_ajax_ajax_request', 'ajax_request' );

function ajax_request() {

$table = array();
$table['cols'] = array(
    /* define your DataTable columns here
     * each column gets its own array
     * syntax of the arrays is:
     * label => column label
     * type => data type of column (string, number, date, datetime, boolean)
     */
    // I assumed your first column is a "string" type
    // and your second column is a "number" type
    // but you can change them if they are not
    array('label' => 'Date', 'type' => 'string'),
    array('label' => 'Variable', 'type' => 'number')
);

$rows = array();
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => "2019-08-26");
$temp[] = array('v' => (int) 3); 
$temp[] = array('v' => "2019-08-24");
$temp[] = array('v' => (int) 5); 
// insert the temp array into $rows
$rows[] = array('c' => $temp);


// populate the table with rows of data
$table['rows'] = $rows;

// encode the table as JSON
$jsonTable = json_encode($table);
echo $jsonTable;

// To return to the front page, always finish after echoing the desired content.
wp_die();
}

This test function works, i.e. sending from Javascript to PHP.

function testAjax() {
    jQuery(document).ready(function($) {
    //We'll pass this variable to the PHP function example_ajax_request
    var car = 'BMW';
    // This does the ajax request
    jQuery.ajax({
    url: ajax_object.ajax_url,
    data: {
        'action':'ajax_request',
        'car' : car
    },
    success:function(data) {
        // The OutPut after successfully receiving content
        console.log(data);
        window.alert("Working test function!");
    },
    error: function(errorThrown){
        console.log(errorThrown);
    }
    });
});
}

I am new to Ajax and I guess there is something in that code which is the problem. I seem to need the data: {'action': 'ajax-request'} for Wordpress, but this is for sending data if I have understood correctly. So where to put this when retrieving data?

Ingrid
  • 516
  • 6
  • 18
  • That ajax request is asynchronous, you need to move all the chart code that uses `jsonData` *inside* the `success` callback. –  Aug 28 '19 at 10:33
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Aug 28 '19 at 10:33
  • Ah, will edit this. Although it doesn't solve my problem, as the error function is called. – Ingrid Aug 28 '19 at 11:20
  • Ok, to the test function works, as in, the `success` callback is called? But the real one doesn't work and `error` is called? Do you see an error message in the console? If you change the error callback to `function(xhr, textStatus, textError) { console.log(textError); }` what do you get? –  Aug 28 '19 at 13:06
  • Yes, that's right. When using your error code, I get this error: `SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data" jQuery 7 parseJSON parseJSON Wb x c send ajax drawGraph https://...javascript.js?ver=1.0.0:34 jQuery 3 i add ready drawGraph https://...javascript.js?ver=1.0.0:32` – Ingrid Aug 28 '19 at 13:24
  • 1
    Ok, so that sounds like there's an error in your PHP code that causes more than just JSON to get sent back. Try removing `dataType: "json"` from the request and simply `console.log()` the reply to narrow down the error. –  Aug 28 '19 at 13:26
  • Thanks, the success callback is then called and it seems the "JSON" data included all my HTML code from the PHP doc as well. If I'm interpreting the console output correctly. Don't know why though... ` ... {"cols":[{"label":"Date","type":"string"},{"label":"Variable","type":"number"}],"rows":[{"c":[{"v":"2019-08-24"},{"v":3}]},{"c":[{"v":"2019-08-26"},{"v":5}]}]}` – Ingrid Aug 28 '19 at 13:31
  • After moving my HTML code to inside a PHP function (instead of outside as I had originally), I get the correct JSON data that can be plotted! Thanks @ChrisG! – Ingrid Aug 28 '19 at 14:13
  • Ah, yeah, that'll do it :) –  Aug 28 '19 at 14:42

0 Answers0