Send data by Ajax, make MySQL query in the background and plot Google chart with the data found

1

Here's a step-by-step guide to what the code I'm about to do is right.

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

In the first place (1) data is sent through a simple form; (2) a query is made in the MySQL database; (3) the resulting array is [to save time and space these last two steps will not be explicitly demonstrated]; (4) returns a variable in the correct format to be used in Google Chart; (5) redirects to the original page (index.php); (6) load index.php again with the graph plotted.

Follow the page codes:

index.php:

<?php
    session_start();
?>
<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script><scripttype="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's worth noting that in this way everything works as expected.

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

Ajax is very new to me and so I am facing these problems. I have read numerous posts on the Internet, but I have not been able to make the "thing" work yet and so I count on your help.

What got me the closest I wanted to have was the following post:

link

But I still find problems.

novo_index.php

<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script></head><body><formaction="" 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>';

Somewhat unorthodox, but it was the best I could do with my meager knowledge in the area. As you can see, they are not enough. : -)

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

Thank you very much in advance for the help.

    
asked by anonymous 13.11.2014 / 13:49

0 answers