user3259138 user3259138 - 2 months ago 17
Javascript Question

PHP to JSON Array Output is Wrong

What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.

PHP code:

$a = array();
while($row = mysqli_fetch_array($result))
$a = array();
$epoch = $row['time'];
$dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);

echo json_encode($a, JSON_UNESCAPED_SLASHES);


"time":"2016-11-14 17:23:00",
"time":"2016-11-14 17:07:59",

The correct output should have
between each object.

What I am ultimately trying to do:

function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> &ensp; <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>&ensp; '+v.price+'&ensp; '+v.timeframe+'</span>');



Each {json},{json} object will have its data printed into a span on an html page.

Appreciate the guidance!


Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it. example:

$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
    //your code here
    $a =  array("time" => ....);

    $results[] = $a; //this will add $a to $results
echo json_encode($results, JSON_UNESCAPED_SLASHES);