1

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!

2
  • First of all in PHP, you put the desired data into an array, then as final message you echo the array using json_encode() for output JS can read. Commented Nov 14, 2016 at 17:35
  • 1st: JSON is not an array. 2. It is a valid JSON 3: EXAMPLE OF JSON: {"a": "b", "c": { "d": "e" }} Commented Nov 14, 2016 at 17:37

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This fixed it. Specifically having the json_encode outside of the loop.
1

Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do

echo json_encode($a, JSON_UNESCAPED_SLASHES);

inside your loop, you output a valid JSON object like:

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

However, when you output the subsequent objects, getting a result like

{
    "time": ...
}
{
    "time": ...
}

You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:

[
  {
    "time": ...
  },
  {
    "time": ...
  }
]

That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.

Comments

0

As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:

$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
    $i++;
    $epoch = $row['time']; 
    $dt = new DateTime("@$epoch");  // convert UNIX timestamp to PHP Date

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

7 Comments

output: [{"time":"2016-11-14 17:42:59","signal":"Buy","symbol":"GBPJPYecn","price":"134.88200","timeframe":"M1","epoch":"1479145379"}][{"time":"2016-11-14 17:42:41","signal":"Sell","symbol":"USOilecn","price":"43.09000","timeframe":"M1","epoch":"1479145361"}]
You're reinitializing $a inside the loop. Also, no reason to use array_push. Its documentation recommends not using it when a [] append will work.
@user3259138 With that output it looks like you still have the echo json_encode(... inside the loop.
Sorry, indeed. I edited my answer. It is now equivalent to tsta's one.
still have $a = array() inside the loop, though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.