My PHP file retrieves data from a PostgreSQL DB. I have to send them back to my jQuery function in two different arrays. One is passed by using:
echo json_encode($tb);
and works fine, in my js file i get data correctly by using:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb) {
console.log(tb);
})
console output is as expected.
The other is always a PHP array, but I have to replace chars:
str_replace(array('[', ']'), '', htmlspecialchars(json_encode($ltb), ENT_NOQUOTES));
but if I write:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb, ltb) {
console.log(tb);
console.log(ltb);
})
console.log(ltb) simply outputs
success
what I'm I getting wrong?
The second parameter of succes
is the response staus. This is the reason because you get success
when logging tlb
.
You can only return one JSON at at time, so combine them:
echo json_encode(array("other stuff", "tb" => $tb, "tbl" => array("some" => "data")));
On JS side you can simple acces them by index or key:
tb[0]; // "other stuff"
tb.tb; // content of $tb variable
tb.tbl; // {some: "data"}
The final working code:
PHP:
$tb = array();
$ltb = array();
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
array_push($ltb, $row["x"], $row["y"]);
array_push($tb, $row["z"],$row["t"]);
}
echo json_encode(array('tb'=>$tb,'ltb'=>$ltb));
JS
$.ajax({
type: "POST",
url: './DB/lb.php',
dataType: 'json', // this is what I forgot!!!
data: {d_p: oa}, // passes variable for PHP function
success: function (response) {
console.log(response.tb+" "+ response.ltb);
$.each(response.tb, function( i, item ) {
// iterate over tb array
}
$.each(response.ltb, function( i, item ) {
// iterate over ltb array
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.