user3259138 user3259138 - 22 days ago 5
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();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$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);
}


Output:

{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}


The correct output should have
},{
NOT
}{
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>');

});
}
//alert(response);
console.log(response);
}

});
}


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

Appreciate the guidance!

Answer

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);