MorRob MorRob - 4 months ago 19
PHP Question

jQuery get json_encode variable from PHP

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?

Answer

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"}
Comments