Send data by Ajax, query Mysql in background and plot Google Chart with found data

Asked

Viewed 572 times

2

Below I present a step-by-step of what the code I will present already performs correctly.

After that I will present the new approach that I would like to use, but which unfortunately is not working.

First (1) data are sent by means of a simple form; (2) a query is made in the Mysql database; (3) it is the resulting array [to save time and space these last two steps will not be explicitly demonstrated]; (4) a variable is returned in the correct format to be used in the Google Chart; (5) redirect to the original page (index.php); (6) index.php is loaded again with the plotted chart.

Follow the page codes:

index php.:

<?php
    session_start();
?>
<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(drawChart);
              function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Área de Conhecimento', 'Quantidade'],
                    <?php echo $_SESSION['chart']; ?>
                ]);
                var options = {
                  title: 'Áreas de Conhecimento'
                };
                var chart = new google.visualization.PieChart(document.getElementById('areas'));
                chart.draw(data, options);
              }
        </script>
    </head>
    <body>
        <form action="chart.php" id="form" method="post" role="form">
            <input id="pub-nr" name="pub-nr" placeholder="Publication Number" type="text" value="" required />
            <input id="submit" type="submit" value="Search">
        </form>
        <?php
            if(isset($_SESSION['chart'])){
                echo '<div id="areas"></div>';
                unset($_SESSION['chart']);
            }
        ?>
    </body>
</html>

Chart.php

<?php
    session_start();

    // Query no banco de dados. Tratamento no array resultante até receber a variável abaixo:
    // Esses passos nao sao demonstrados aqui por nao serem essenciais para a solucao do problema.

    $chart = "['Ciências Humanas', 8],
              ['Ciências Sociais', 6],
              ['Filosofia',  4],
              ['Política', 2],
              ['Retórica', 1]";

    $_SESSION['chart'] = $chart;

    // Redirecionamento de volta para index.php
    header('Location: index.php');

It is worth noting that in this way everything works as expected.

Now the problem: Following the best practices for web development, I would like to accomplish the same thing described above, but with Ajax, to prevent the entire page from being reloaded.

Ajax is too young for me and that’s why I’m facing these problems. I have read numerous posts on the Internet, but I could not make the "thing" work yet and so I count on your help.

What got me closer to what I would like to have was the following post:

https://stackoverflow.com/questions/24729526/ajax-and-google-charts-passing-php

But still I find trouble.

new_index.php

<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    </head>
    <body>
        <form action="" id="form" method="post" role="form">
            <input id="pub-nr" name="pub-nr" placeholder="Publication Number" type="text" value="" required />
            <input id="submit" type="submit" value="Search">
        </form>
        <div id="ajax"></div>
        <script type="text/javascript">
            $(function(){
                $('form#form').submit(function(){
                    $.ajax({
                        url: 'chart.php',
                        type: 'POST',
                        data: $('form#form').serialize(),
                        success: function(response) {
                            $('div#ajax').html(response);
                        }
                    });
                    return false;
                });
            });
        </script>
    </body>
</html>

new_chart.php

<?php

    // Query no banco de dados. Tratamento no array resultante até receber a variável abaixo:
    // Esses passos nao sao demonstrados aqui por nao serem essenciais para a solucao do problema.

    $chart = "['Ciências Humanas', 8],
              ['Ciências Sociais', 6],
              ['Filosofia',  4],
              ['Política', 2],
              ['Retórica', 1]";

    echo '<script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
              function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    [\'Área de Conhecimento\', \'Quantidade\'],
                    <?php echo $chart; ?>
                ]);
                var options = {
                  title: \'Áreas de Conhecimento\'
                };
                var chart = new google.visualization.PieChart(document.getElementById(\'areas\'));
                chart.draw(data, options);
              }
        </script>
        <div id="area"></div>';

A bit unorthodox, but it was the best I could do with my poor knowledge in the area. As it turns out, they are not enough. :-)

Hence the question: what would I have to modify in the (original) codes so that I can print the chart using Ajax, i.é without having to reload the page? Please do not consider a high prior knowledge in Ajax and mainly in json. A concrete functional example would be very welcome. ;-)

Many thanks in advance for the help.

  • 1

    Welcome to the site, Heloisa :) There is an important step in AJAX that is to make your chart.php work alone to generate a string or array, which is what will be returned pro JS to fill the desired content; once running alone, connect to JS. . . . So, looking over, I would try to run the google script there on index.php from simplified AJAX data.

  • Hello @brasofilo, thanks for your reply! I’m here breaking my head and still nothing... Chart.php seems to work by itself yes. If I only upload this file it gives me the expected string, if I give an echo. What I’m not able to do is this "devolucao" for the JS or even this connection to the JS. Then you spoke Greek... :-) The problem with running the script in index.php is that it is loaded before I run the query that gives me exactly the data to fill the graph. Or am I thinking wrong?

  • PS: And thanks for the tips. Little by little I understand how to use the site.

  • In fact, it was just a few comments in the form of a commentary; replies themselves are published below. I’m in no condition to test now, nor have I ever used the google.visualization, but I don’t understand why you’re using $_SESSION... And that function drawChart() in the index.php it’s okay if $_SESSION['char'] is not set?

  • Hello brasofilo the first 2 files have no problems and are not the subject of my doubt. What I would do with them is this: send index.php data to Chart.php through the index.php form. In Chart.php the query is done and the final result is a string that I insert into this Session variable. Then I would send everything back to index.php and then drawChart() had the data (which came by $_SESSION['Chart']) to draw the graph. If this variable is not present there is no problem at all. Only the graph will not be drawn. My problem is how to do the same using ajax.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.