How to get JavaScript variable through PHP post request?

Tekson :

I am posting the PHP file (post.php) through jquery ajax. And I want to get the data from it in the form of a javascript variable. I successfully get the data in my console. But I don't know how can I use this variable. You can see my code below.

$.post(
    "post.php",
    {
      region: region,
      district: district
    },
    function(data) {
      console.log(data);
    }
  );

my post.php page looks like this

    @include('../../_partials/_dbConnect.php');
    $region = $_POST['region'];
    $district = $_POST['district'];
    $sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
    $result = pg_query($db_connection, $sql);
        while ($row = pg_fetch_row($result)) {
            $cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
        }
<script>
  var cols = [<?php echo '"'.implode('","', $cols).'"' ?>];
</script>

And the console.log(data) output like this,

<script>
  var cols = ["94","32","361","0","118","159","0","243","702","1775","8","0","2","0","150","135","381","2","0","0","0","0"];
</script>

Your help is highly appreciated.

Thum Choon Tat :

In your post.php, you can simply echo the array and jQuery should automatically convert it to an array as the response

// post.php
<?php
    @include('../../_partials/_dbConnect.php');
    $region = $_POST['region'];
    $district = $_POST['district'];
    $sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
    $result = pg_query($db_connection, $sql);

    while ($row = pg_fetch_row($result)) {
        $cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
    }

    echo json_encode($cols);
?>

// Somewhere in your js
$.post(
    "post.php",
    {
      region: region,
      district: district
    },
    function(data) {
      console.log(data[0]);
    }
);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29802&siteId=1