Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get JavaScript variable through PHP post request?

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.

like image 493
Tekson Avatar asked Aug 14 '26 00:08

Tekson


2 Answers

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]);
    }
);
like image 99
Thum Choon Tat Avatar answered Aug 15 '26 13:08

Thum Choon Tat


in javascript use JSON.parse()

$.post(
    "post.php",
    {
      region: region,
      district: district
    },
    function(data) {
      data=JSON.parse(data);
    }
);```

And here you go, u can play with it as you need
Happy learning!
like image 38
Sadak Avatar answered Aug 15 '26 15:08

Sadak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!