hnewbie hnewbie - 1 month ago 6
JSON Question

Return multiple values through Jquery post()

I've returned 2 dates from a PHP script through

$.post()
. Then I'm trying to break up the results into two variables (the commented out portion under the console.log) , instead of appearing in one variable.

Below is the jquery code:

$.post('api/displayDBSetTimes.php', function(data) {
var obj = JSON.parse(data);
var htmlToInsert = obj.map(function (item) {
console.log(item.DB_ST);

/* var db_st = item.DB_ST;
var db_et = item.DB_ET;
return db_st + " " + db_et;*/
return item;

});
$('#oecd').html(htmlToInsert);
});


The PHP is below. I formatted the dates in the PHP script before sending out in JSON. The commented out jquery code above worked before I formatted the dates in PHP:

<?php
include_once("../include/sessions.php");
$select = "SELECT start_time AS DB_ST, end_time AS DB_ET FROM countdown WHERE tid = 1;";
$query = mysqli_query($dbc, $select);

if($query){
$out = array();
while ($row = $query->fetch_assoc())
{
$out[] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ST']));
$out[] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ET']));
}

// encode array as json and output it for the ajax script
echo json_encode($out);
}
?>


Every time I try to refer to the PHP variable in the jQuery
$post()
function (ie.
item.DB_ST
in the console.log) it returns as
undefined
, but if I remove the PHP variable reference, the 2 dates come back as one big string. I don't want that. I don't know why it's coming back undefined if I reference one part of the array.

Could someone help me? Would
ajax()
be better for something like this? The help would be much appreciated.

Answer Source

Set associative arrays in your PHP file...

$out['DB_ST'] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ST']));
$out['DB_ET'] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ET']));

And in your $.post you have to indicate the response is going to be in JSON format...

$.post('api/displayDBSetTimes.php', function(data) {

    /* Here you can access directly to data.DB_ST and data.DB_ET */

},'json');

I hope it helps.