Reputation: 2337
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.
Upvotes: 3
Views: 210
Reputation: 911
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!
Upvotes: 2
Reputation: 3090
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]);
}
);
Upvotes: 2