Is it possible to return a vector to a javascript

1

I am developing customizable graphics by users where they can select the options they want by sending the parameters to the php that searches the sql and returns me what I want. For graphics I'm using highcharts. But I'm having a hard time understanding how I return the vector of my function to js. I'm using jquery so I do not need to refresh the page. But when I do

$.post('envia.php', {nome: nome}

It performs the search of the data, but I do not know how I get this data back to my page where the graphs are generated. Would anyone know the solution?

    
asked by anonymous 28.01.2015 / 14:15

2 answers

7

The data returns in the callback method of $.post :

$.post('envia.php', {nome: nome}, function(dados) {
    // use os dados aqui
    // o uso exato vai depender do formato que o PHP
    // usou para serializar os dados para envio
});

It seems like you want to return objects to JS, so PHP would have to send a JSON:

<?php
$vetor = array('x' => 10, 'y' => 20);

// envia dos dados para o cliente
header('Content-Type: application/json');
echo json_encode($vetor);
?>

Then you could use it like this:

$.post('envia.php', {nome: nome}, function(dados) {
    console.log(dados.x, dados.y);
});
    
28.01.2015 / 14:33
2

The third parameter of the post function is a callback that receives the server data as a parameter.

$.post('envia.php', {nome: nome}, function(dados) {
    console.log(dados);
});

On the server, you can do something like this:

$dados = array( ... );
echo json_encode($dados);
    
28.01.2015 / 14:41