Send array to PHP via Ajax

0

I want to send a vector from javascript to PHP. I have the following code but it is not working. How to do it?

    info = [];
    info[0] = 'thiago';
    info[1] = 'carlos';

    alert(info[0]);

    $.ajax({
        type: "GET",
        data: {info:info},
        url: "buscar.php",
        success: function(msg){
            console.log(msg);
        }
    });
    
asked by anonymous 06.03.2018 / 20:01

2 answers

2

According to your javascript:

 info = [];
    info[0] = 'thiago';
    info[1] = 'carlos';

    alert(info[0]);

    $.ajax({
        type: "GET",
        data: {info:info},
        dataType : 'json', 
        url: "buscar.php",
        success: function(msg){
            console.log(msg);
        }

Your php can do so to receive the vector and it follows a foreach for you to test:

<?php
    $teste = $_GET['info'];

    foreach( $teste as $key => $value ){
        echo "{$value}\n";
    }   

?>

And if you who returns on your console.log()

You can paste it into php just like this:

<?php
    $teste = $_GET['info'];

    echo json_encode( $teste )  ;

?>

Hope you can help

    
06.03.2018 / 20:46
2

Your javascript should look like this:

var info = [];
info[0] = 'thiago';
info[1] = 'carlos';

$.ajax({
    type: "GET",
    data: {info:info},
    url: "buscar.php",
    dataType: "json",
    success: function(msg){
        console.log(msg.info[0]);
    }
});

Your php like this:

echo json_encode($_GET);

To get the data on the server side use this:

$_GET['info'][0];
    
06.03.2018 / 20:26