Once again on how to plot google chart after ajax call

BEGINNING OF WORK

Since I haven't received any response, I'll try to explain or better show what worked for me (without ajax) and doesn't work now when I try to use ajax. Since examples speak more than words, I'll write the essential parts of the codes.

I had two files, namely index.php, where is the input form and where the graph is plotted, and script.php, which gets what was inserted into the form, makes a request with it and returns a variable that is returned to index. php just to be used in google stuff.

So here you are:

index.php

<?php
    session_start();
?>

<!DOCTYPE html>
<html lang="en">
    <head>
    <!-- Google Charts -->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
        google.setOnLoadCallback(drawChart01);

        // CHART 01
        function drawChart01() {
            var data = google.visualization.arrayToDataTable([
                ['Technological Area', 'Number of Publications'],
                <?php echo $_SESSION['techAreas03']; ?>
            ]);

            var options = {
                chartArea: {width:'100%',height:'100%'},
                forceIFrame: 'false',
                is3D: 'true',
                pieSliceText: 'value',
                sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
                titlePosition: 'none'
            };

            var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
            chart.draw(data, options);
        }
    </script>
    </head>

    <body>
        <form id="publn-nr-srch" action="script.php" method="post" role="form">
            <input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
            <input id="btn-srch" type="submit" value="Search">
        </form>

        <?php
            if(isset($_SESSION['techAreas03'])){
                echo '<div id="tech-areas"></div>';
            }
        ?>
    </body>
</html>

      

and script.php:

<?php
session_start();

# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));

while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
    $techAreas00[] = ($r['techarea']);
}

# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));

# Count values.
$techAreas02 = array_count_values($techAreas01);

# Sort array.
arsort($techAreas02);

# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '[\''.$k.'\','. $v.']'; }, $techAreas02, array_keys($techAreas02)));

$_SESSION['techAreas03'] = $techAreas03;

# Reload index.php, but now with the variable $techAreas03 that will be used in the head to populate the GOOGLE CHART.
header(Location: index.php);

      

This work is wonderful.

Now when I try to use ajax to avoid reloading index.php I cannot build charts. The problem is that the Google script has already been loaded before the script.php creates the variable. More details on the issue in the original answer below.

And here are the codes of the changed pages:

index.php

<?php
    session_start();
?>

<!DOCTYPE html>
<html lang="en">
    <head>

    <!-- Google Charts -->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
        google.setOnLoadCallback(drawChart01);

        // CHART 01
        function drawChart01() {
            var data = google.visualization.arrayToDataTable([
                ['Technological Area', 'Number of Publications'],
                <?php echo $techAreas03; ?>
            ]);

            var options = {
                chartArea: {width:'100%',height:'100%'},
                forceIFrame: 'false',
                is3D: 'true',
                pieSliceText: 'value',
                sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
                titlePosition: 'none'
            };

            var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
            chart.draw(data, options);
        }
    </script>
    </head>

    <body>
        <form id="publn-nr-srch" action="" method="post" role="form">
            <input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
            <input id="btn-srch" type="submit" value="Search">
        </form>

        <div id="ajax"></div>

    </body>
    <script type="text/javascript">
    $(function(){
        $('form#publn-nr-srch').submit(function(){
            $.ajax({
                url: 'script.php',
                type: 'POST',
                data: $('form#publn-nr-srch').serialize(),
                success: function(response) {
                    $('div#ajax').html(response);
                }
            });
            return false;
        });
    });
    </script>
</html>

      

and here's script.php:

<?php
session_start();

# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));

while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
    $techAreas00[] = ($r['techarea']);
}

# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));

# Count values
$techAreas02 = array_count_values($techAreas01);

# Sort array.
arsort($techAreas02);

# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '[\''.$k.'\','. $v.']'; }, $techAreas02, array_keys($techAreas02)));

      

In my research on the problem, I found many threads that talked about a callback function to plot a graph using ajax, but if we already have the data that is plotting the chart. The problem is that I didn't find an answer specific to my problem, because I need to send other data via ajax (namely post number = publn-in), the request starts and the result of this request is the data that will be used by the graph Google.

Hopefully now I can be clearer and that you guys can help me.

As mentioned, more information is below and you can ask more at any time.

Many thanks!

EDIT END

INITIAL BEGINNING AFTER

I have a form that I am using to submit information to a php script via ajax.

This script will get this information, query the database, and return me an array, which I convert to a string.

This string will be used to build a Google chart. I was looking for how I could plot the graph after the ajax call, but I was unable to get the expected results.

The problem is that it has already been loaded and we have to use a callback to plot the graph.

Here's my code:

<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>

        <script type="text/javascript">
            google.load("visualization", "1", {packages:["corechart"]});
            google.setOnLoadCallback(drawChart04);
            function drawChart04() {
                var data = google.visualization.arrayToDataTable([
                    ['Publication', 'Similarity'],
                    <?php echo $chart; ?>
                ]);

                var options = {
                    chartArea: {width:'80%',height:'80%'},
                    forceIFrame: 'true',
                    titlePosition: 'none',
                    hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
                    legend: {position: 'none'}
                };

                var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
                chart.draw(data, options);
            }
        </script>
    </head>

    <body>
        <form id="publn-nr-srch" action="" method="post" role="form">

            <input class="form-control" id="publn-in" name="publn-in" placeholder="Publication Number" type="text" value="" required />

            <input id="btn-srch" class="btn btn-sm btn-primary" type="submit" value="&nbsp;Search&nbsp;">

        </form>

        <div id="ajax"></div>

    </body>

    <script type="text/javascript">
    $(function(){
        $('form#publn-nr-srch').submit(function(){
            $.ajax({
                url: '../models/pubSearchScr.php',
                type: 'POST',
                data: $('form#publn-nr-srch').serialize(),
                success: function(response) {
                    $('div#ajax').html(response);
                }
            });
            return false;
        });
    });
    </script>
</html>

      

After running the script, I get, for example, the following line in a variable (everything works well here):

$chart = "['1977',8], ['1978',31], ['1979',48], ['1980',34], ['1981',30], ['1982',37], ['1983',28], ['1984',31], ['1985',40], ['1986',32], ['1987',44], ['1988',42], ['1989',45], ['1990',43], ['1991',36], ['1992',31], ['1993',34], ['1994',26], ['1995',25], ['1996',41], ['1997',35], ['1998',27], ['1999',25], ['2000',14], ['2001',31], ['2002',19], ['2003',16], ['2004',21], ['2005',20], ['2006',12], ['2007',16], ['2008',29], ['2009',10], ['2010',13], ['2011',22], ['2012',2], ['2013',2]";

      

which I am using in google stuff (see above also in main session):

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart04);
    function drawChart04() {
        var data = google.visualization.arrayToDataTable([
            ['Publication', 'Similarity'],
            <?php echo $chart; ?>
        ]);

        var options = {
            chartArea: {width:'80%',height:'80%'},
            forceIFrame: 'true',
            titlePosition: 'none',
            hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
            legend: {position: 'none'}
        };

        var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
        chart.draw(data, options);
    }
</script>

      

In the script, also I have the following variable which is reflected in the ende. In ende, I can see the html file on the screen, but not the graph:

$output = '
            <!-- Similarity Curve -->
            <div class="col-md-6">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            <i class="fa fa-line-chart"></i>
                            Similarity Curve
                        </div>
                    </div>
                    <div class="panel-body">
                        <div id="sim-curve"></div>
                    </div>
                </div>
            </div>';

echo $output;

      

I understand the problem that the google map info head is already loaded without the $ chart variable before I run the ajax call. Then when I start everything goes well, but the diagram cannot be plotted. In my research, I read about callback function, etc., and I thought it was already in my code. If not, what is needed in my case and WHERE? In the head, or in the middle of the html code, or in the script?

One piece of advice: when I do the same without ajax, namely using an html form that submits information to the php script and script, then redirects back to the file, everything works fine because the head is loaded again with the entire page. My problem is when should I use awesome ajax.

Any help would be appreciated. Thank you very much in advance.

ORIGINAL LAST

+3


source to share


1 answer


First, you have to create a function that is used to draw google chart with chart data input.

Example: drawChart(inputData) = drawChart04(data);

      

Second, you create a variable that stores the chart data:

//var inputData = your data;
var inputData = google.visualization.arrayToDataTable([
        ['Publication', 'Similarity'],
        <?php echo $chart; ?>
    ]);

      

Third, you should know how to return data using ajax on the server (PHP):



Example: dataChart = you query or to do something to get it;
echo json_encode(dataChart); exit; //This is just an example.

      

Fourth, you must know how to transfer data from PHP to Javascript. I mean, when you get a response, you should know how to create an inputData base for the response.

$.ajax({url: "....php", type: "POST", dataType: "json", data:{..}})
.done(function(response){
   inputData = response; //You have to convert response to inputData. Maybe Json.parse(response).
   //I don't know, You have to know that you response. So find the best way to create inputData.
   drawChart(inputData);//And finally call this function
});

      

What is it. I think you can understand what I was talking about above. If you can't fix it. Let me know my skype. I will fix it for you. SkypeID: jewelnguyen8

+3


source







All Articles