pass several php arrays to javascript

0

the following php code that generates two arrays

<?php
    //los datos salen de una tabla mysql
    $last_year_sales = [2589, 2589, 1478, 2587, 7852, 9632];    
    $current_year_sales = [1250, 1480, 1156, 3589, 7521, 9632];

    //enviar
    echo json_encode($last_year_sales);
    echo json_encode($current_year_sales);
?>

I need to receive them on another page and I do so

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       var last_year = JSON.parse(this.last_year_sales);
       var current_year = JSON.parse(this.current_year_sales);
    }

This comes

[2589, 2589, 1478, 2587, 7852, 9632][1250, 1480, 1156, 3589, 7521, 9632]

How do I request the two arrays? or how do I do with ajax?

Thank you.

    
asked by Juan Carlos 04.08.2018 в 18:01
source

2 answers

1

It can be solved in several ways I give you an example, using your context.

index.php

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head> 
</html>

<script>
$.ajax({
    type: 'POST',
    url: 'test.php',
    datatype: 'text'
    }).done(function (response) 
    {
        resultado = JSON.parse(response);
        console.log(resultado["last_year_sales"]);
        console.log(resultado["current_year_sales"]);
    });
</script>

test.php

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $last_year_sales = [2589, 2589, 1478, 2587, 7852, 9632];    
        $current_year_sales = [1250, 1480, 1156, 3589, 7521, 9632];
        $respuesta["last_year_sales"] = $last_year_sales;
        $respuesta["current_year_sales"] = $current_year_sales;
        echo json_encode($respuesta);
    }
?>

Greetings.

    
answered by 04.08.2018 / 20:34
source
0

Put them in an associative PHP arrangement

<?php
    $arr = array();

    //los datos salen de una tabla mysql
    $last_year_sales = [2589, 2589, 1478, 2587, 7852, 9632];    
    $current_year_sales = [1250, 1480, 1156, 3589, 7521, 9632];

    $arr['last_year_sales'] = $last_year_sales;
    $arr['current_year_sales'] = $current_year_sales;
    //enviar
    echo json_encode($arr);
?>

In JS you're going to catch them like you do.

   var last_year = JSON.parse(this.last_year_sales);
   var current_year = JSON.parse(this.current_year_sales);
    
answered by 04.08.2018 в 18:18