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> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+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!
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);
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.
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);
Related
I have a JSON array being passed form PHP and it looks like this:
[{from: "2019,09,14", to: "2019,09,14"}]
and I need it to look like this:
[{from: [2019, 9, 14], to: [2019, 9, 17]}]
here is my code thus far:
function getPricingDateRanges() {
var city = document.getElementById("pricingcityselect").value;
$.ajax({
url: 'getpricingdaterangepicker.php?city=' + city, // Change this to the uri of your file
method: 'GET', // Use the GET method
dataType: 'json', // Expect a JSON response
success: function(response) { // What will happen when the request succeeds
var darray = [{from:[2019,9,14], to:[2019,9,17]}];
console.log(response);
console.log(darray);
}
});
}
Added code from my PHP:
<?php
include 'dbconfig.php';
$city = ($_GET['city']);
$sql="SELECT start_date, end_date FROM date_ranges WHERE city='" . $city . "'";
$result = mysqli_query($conn,$sql);
// Create empty array.
$date_ranges = array();
// Add every row to array;
while($row = mysqli_fetch_array($result)) {
// Create an associative array to store the values in.
// This will later be a JavaScript Object.
$from = new DateTime($row['start_date']);
$ffrom = $from->format('Y,m,d');
$to = new DateTime($row['end_date']);
$fto = $from->format('Y,m,d');
array_push($date_ranges, array(
'from' => $ffrom,
'to' => $fto
));
}
// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>
First, it's important to point out that the "JSON" you've included is not JSON. It is neither a string, nor are the property names quoted.
However, if this is actually the input you're dealing with, you can loop through the items, split the from and to values on ,, and use .map(Number) to convert them to integers.
const arr = [{from: "2019,09,14", to: "2019,09,14"}];
//Helper function to split on comma, convert items to numbers
const toIntegerArray = str => str.split(",").map(Number);
const result = arr.map(({from,to}) => ({
from: toIntegerArray(from),
to: toIntegerArray(to)
}));
console.log(result);
Parse JSON till the point with "2019,09,14".
then "2019,09,14" convert to array of numbers by:
"2019,09,14".split(',').map(el => parseInt(el, 10))
I'm training myself (JSON and PHP) and I have a problem
I have Json decode look like this :
"playerstats": {
"steamID": "75068112",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 2314497
},
{
"name": "total_deaths",
"value": 1811387
},
And to parse into php i do :
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['playerstats']['stats'][1]['name']
And it works but the problem is when i change the id to get stats, the order of the array isn't the same :/
So i can't use [2] or any else number to get data.
I post here to know how could'i get stats using the attribute name of each array ('total_kills' for example) instead of [1]..[2]..
thanks for all your support
Use foreach and use if condition to check the name is 'total_kills' is true then store it into new array like this .
<?php
$json = json_decode($content, true);
$new_array =array();
$i=0;
foreach($json['playerstats']['stats'] as $row )
{
if($row['name']=='total_kills')
{
$new_array[]=array($row['name']=>$row['value']);
}
if($i<10)
{
break;
}
$i++
}
print_r($new_array);
?>
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['playerstats']['stats'] as $row )
{
echo $row['name'];
echo $row['value'];
}
What you're looking for is a way to loop over the array. In PHP you can do the following;
$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json["playerstats"]["stats"] as $stat){
if($stat["name"] == "total_kills"){
echo "total kills: ".$stat["value"];
}
elseif($stat["name"] == "total_deaths"){
// ...
}
// etc... continue to select all parameters you would like
}
This will allow you to get the value for each stat with name using the if else statement.
Another way to do something with all objects in an array is to use the array_map() function, which takes another function as one of its arguments. Using this whenever you can will force you to adhere to good programming practices, because the passed in function cannot modify values outside of the array and arguments passed in via use.
I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!
I am having a difficulty retrieving a series of json data from php to my JavaScript, file..
Firstly, I have a series of json data stored in an array in php, and echoing each by wrapping it in the for loop to my JavaScript file,
<?php
$result = array('{"one": "test","two": "test"}','{"three": "test","four": "test"}');
for ($i = 0; $i < count($result); ++$i) {
echo $result[$i];
}
?>
in my JavaScript,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
My console does not display anything at all, not recognizing each array element as a json..
but if I send just one array element specifically, for example,
echo $result[0];
then it successfully displays,
Object {one: "test", two: "test"}
why can't I pass a series of json data in an array from php in my ajax call?
It doesn't work because you are generated malformed JSON. The output of your script is
{"one": "test","two": "test"}{"three": "test","four": "test"}
When you access the first element of the array only you get
{"one": "test","two": "test"}
Which is valid.
PHP has json_encode which will do this work for you, so your code would become
$result = array(
array('one' => 'test', 'two' => 'test'),
array('three' => 'test', 'four' =>'test')
);
echo json_encode($result);
giving the output
[{"one":"test","two":"test"},{"three":"test","four":"test"}]
Your code will output this:
{"one": "test","two": "test"}{"three": "test","four": "test"}
This is invalid JSON, so obviously will not work. (Try parsing it with JSON.parse and you'll see.)
You actually need to send the data as an array, so replace your for loop with a simple json_encode call:
echo json_encode($result);
This will output
[{"one": "test","two": "test"},{"three": "test","four": "test"}]
This is valid JSON, and can be parsed into a Javascript array.
Also can you this script
function doj($json){
$result = json_encode($json);
return json_decode($result, true);
}
$json = array(
'{"one": "test","two": "test"}',
'{"three": "test","four": "test"}'
);
$j = doj($json);
foreach($j as $k=>$v){
$extractagain = json_decode($v);
print_r($extractagain);
}
and the output is:
stdClass Object ( [one] => test [two] => test ) stdClass Object ( [three] => test [four] => test )
I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.