Run script generated with PHP after loading AJAX

1

I have put the following javascript test code but it does not run after loading the page with AJAX.

<script> alert('hi'); </script>

My AJAX code (in functions.js):

function mostrarAJAX(enlace, elem)
{
    $.ajax
    ({
        url: enlace,
        cache: false,
        beforeSend: function() { $(elem).html('<br /><center style="margin- 
        top: 50px;"><span style="margin-right:8px;"></span><img 
        src="../images/loading.gif" /><div style="font-size: 20px;margin- 
        top: 25px;">Loading...</div></center>'); },
        error: function(xhr) { $(elem).html(xhr.status + ' ' + xhr.statusText); },
        success: function(result){ $(elem).html(result); }
    });
}

When I run the AJAX, the page is displayed, but the script is not executed. The thing is that part of the javascript I generate it from PHP with echo, since it is a statistic chart.

Hunk of the real javascript (in stats.php):

data: 
[
  <?php
    $resultstats = mysqli_query($con, $sqlstats);
    $countstats = mysqli_num_rows($resultstats);
    for($i = 0; $i < $countstats; $i++)
    {
        $rowstats = mysqli_fetch_array($resultstats);

        if($i < ($countstats - 1))
            echo '{date: "'.$rowstats['Date'].'", value: '.$rowstats['TotalMembers'].'}, ';
        else
            echo '{date: "'.$rowstats['Date'].'", value: '.$rowstats['TotalMembers'].'}';
    }
    ?>  
],

The PHP script runs correctly by filling in the javascript array with the statistics for the graph but the problem is that the javascript is not executed, so the graph is not displayed. When I run the graph without AJAX, the graph works correctly.

Any ideas?

Thanks in advance.

    
asked by Emilio 06.08.2018 в 14:03
source

2 answers

1

Instead of sending the final code, try sending only the data and then in the client you interpret it and execute it.

With your example of alert('hi') , send the response of the text hi and show it with a alert :

In the php:

echo 'hi';

In your js:

$.get(url, function(mensaje){
   alert(mensaje);
})

You could do the same with the graph data. Simply send the data and add it to the graph.

In your php you would have:

echo json_encode(data);

And in your js you would have:

$.get(url, function(data){
   console.log(data); // [...]
});

This is because if you send the code as such, you will have to interpret it with eval() , something that is not recommended if you do not know how to handle it.

    
answered by 06.08.2018 / 14:38
source
0

For those who can help you, as the browser does not execute the explicit javascript codes after an AJAX call, I had to do the following:

stats.html:

<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js" type="text/javascript"></script>
<script src="/js/MemberStats.js" type="text/javascript"></script>

<div class="inicio-top-h1">Miembros Registrados</div>
<div id="TotalMembers" style="height: 400px; width: 100%;"></div>

<div class="inicio-top-h1">Miembros Activos</div>
<div id="ActiveMembers" style="height: 400px; width: 100%;"></div>

<div class="inicio-top-h1">Horas Online</div>
<div id="TotalTime" style="height: 400px; width: 100%;"></div>

<div class="inicio-top-h1">Horas Online Semanales</div>
<div id="TimeWeek" style="height: 400px; width: 100%;"></div>

<div class="inicio-top-h1">Registros Semanales</div>
<div id="RegWeek" style="height: 400px; width: 100%;"></div>

MemberStats.js:

function mostrarGrafico(columna)
{
$.get('GetStats.php', {column: columna}, 
    function(datos)
    {
        Morris.Line
        ({
          // ID of the element in which to draw the chart.
          element: columna,
          // Chart data records -- each entry in this array corresponds to a point on
          // the chart.
          data: JSON.parse(datos),
          xkey: 'date',
          ykeys: ["value"],
          labels: [columna],
        });
    }
);
}

mostrarGrafico('TotalMembers');
mostrarGrafico('ActiveMembers');
mostrarGrafico('TimeWeek');
mostrarGrafico('TotalTime');
mostrarGrafico('RegWeek');

GetStats.php:

<?php
require 'conexion.php';
$columna = $_GET['column'];

$sqlstats = "SELECT * FROM statistics";
$resultstats = mysqli_query($con, $sqlstats);
$countstats = mysqli_num_rows($resultstats);

$lista = array();
while($rowstats = mysqli_fetch_array($resultstats))
    $lista[] = array('date' => $rowstats['Date'], 'value' => $rowstats[$columna]);

echo json_encode($lista);
?>
    
answered by 07.08.2018 в 11:26