good afternoon developers, i have fetch data from my api and the data is responded as below
{id: 1, owner: "2", amount: "0", created_at: "2020-09-14 11:04:12", updated_at: "2020-09-14 11:04:12"}
and my code is below
return this.http.post(this.env.API_URL + "auth/wallet", {
id: this.user['id'],
}).subscribe(res => {
this.wallet = res[0];
console.log(this.wallet);
}, (err) => {
console.log(err);
});
when i type {{wallet["amount"}} it returns Cannot read property 'amount' of undefined
You probably need to use the optional chaining operator with dot notation like this:
{{wallet?.amount}}
This will not throw an error when the value is undefined, because it IS undefined until your API request is completed. By the way, this has nothing to do with Ionic, it's more of an Angular thing.
I chose to use JIT.js rgraph for a project I am working on. What I've done was taken the examples and began slowly merging the js into the projects core files. Simple! The hang up I've run into has me literally stumped.
example.js has (assumed to be hand written at some point) json like so.
var json = {
id: "190_0",
name: "Pearl Jam",
children: [{
id: "306208_1",
name: "Pearl Jam & Cypress Hill",
data: {
relation: "<h4>Pearl Jam & Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam <div>(relation: collaboration)</div></li><li>Cypress Hill <div>(relation: collaboration)</div></li></ul>"
},
children: [{
id: "84_2",
name: "Cypress Hill",
data: {
relation: "<h4>Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam & Cypress Hill <div>(relation: collaboration)</div></li></ul>"
},
children: []
}]
},...
I need the json file dynamically generated in a sense and the most productive way for me to use the json is to create a static file if/when relative parts of the project are updated instead of generating json every time the page loads. Makes sense right?
json.php looks like this
$project = array(
"id" => "1",
"name" => "Testing Project",
"children" => array (
"id" => "2",
"name" => "Sub 1",
"data" => array(
"relation" => "<h4>Testing Project</h4><b>Structure:</b><ul><li>Sub1</li><li>Section 1</li></ul>"
),
"children" => array(
"id" => "3",
"name" => "Section 1",
"data" => array(
"relation" => "<h4>Section 1</h4><b>Structure:</b><ul><li>Testing Project</li><li>Sub 1</li></ul>"
),
"children" => ''
)
)
);
// header('Content-type: application/json'); /* DOES NOTHING */
echo json_encode($project);
my Arrays are hand written at the moment to make sure the process works as intended before programmatically generating the arrays from the database. There are other pieces to the puzzle I do not believe are at all involved at this time but the next piece we need to look at is the ajax call to fetch json.php which is in my custom.js file.
function init() {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': true,
'url': 'js/json.php',
'dataType': "json",
'success': function (data) {
json = data;
console.log(data);
}
});
return json;
})(); ... continue with JIT.js functions
I added console.log(data) to see if the json was coming back formatted and this is what that looks like console.log screenshot using custom.js ajax call So then I reused the example.js file and console.log(data) give us console.log screenshot using example.js
The only obvisou difference is that the example.js json is be represented as an array, not an object. Even stranger still is that when I run the example using the custom.js file with the ajax call "Testing Project" does appear on the graph but no children elements. In the screenshot for custom.js console.log shows all the children elements as children: object, not children:Array[] like example.js
My first thought was to see if I can ensure that all json_encoding forced the associative arrays into "arrays". And yea... lots of time wasted looking at the obvious. So my next thought was it must be in the formatting. example.js used [{ for each child element but json_encode does not. I cannot locate any information to confirm if that really is the problem or not, but, none the less I cant rule that out. I also checked into sequential indexes. example.js certainly does not have sequential indexes. I even went ahead and sorted the arrays before encoding json_encode(array_values($project)); to see what happens and while it outputs to a browser with indexes it of course shows nothing in the graph.
I feel like im spinning in circles ( not in the good eagle circling prey kinda way ) but getting to far off focus to figure this out. I need some fresh perspective and ideas what might be going wrong.
**Edit
I've also tried to convert the strings manually with PHP. still not working. Any ideas?
WOW, Just over 24 hours and I end up doing something like this. It works by making each child with content an array of arrays.
$test = array(
'id' => "1",
'name' => "testing sample",
'children' => array(
array(
...
),array(
...
'children' =>array(),
),
)
);
echo json_encode($test);
JSON is quite confusing and I haven't been able to find a post that can help me so I decided to ask the question myself.
Quick Summary
I need my php array to show up as [object Object] for every array containing an id, label,and type -- when passed through to my JavaScript using json. Here is what I've tried:
if( $node_id == NULL ) {
echo json_encode(array(
0 => array( array("id" => 1, "label" => "A lunch", "type" => "folder"), array("id" => 2, "label" => "A lunch", "type" => "folder"))
));
}
When I run this code I keep getting my alert to display:
{"0":{"0":{"id":1,"label":"A lunch","type":"folder"},"1":{"id":2,"label":"A lunch","type":"folder"}}}
when it should look like
[object Object],[object Object]
so could someone please help convert it to that format through json, or however it might be done?
You're alerting a string, so it seems that jQuery is not recognizing your response as JSON, and it is not being parsed. Try this:
$.ajax({
url : "php/resource.php",
data : { node_id: node_id },
dataType : "json"
}).done(function(data) {
alert(data);
return callback(null, data);
}).fail(function() {
return callback("AJAX error");
});
Also, you may set content type to application/json in your php
header('Content-Type','application/json');
I am trying to use javascript Highcharts to display a chart of rankings from JSON data. I can't seem to get the chart to display.
This is the javascript code:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'drawing',
zoomType: 'x',
width: 900,
height: 222
},
exporting: {
enabled:true
},
title: {
text: url+' - '+keyword
},
credits: {
text: '****',
href: 'http://***/'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%b %e '
}
},
yAxis: [{
//min: 1,
allowDecimals: false,
reversed: true,
///: .2,
//maxPadding: .2,
title: {
text: 'Rankings'
}
},],
tooltip: {
crosshairs: true,
shared: true
},
series: [{}]
};
var url = "http://*******/chart.php";
$.getJSON(url, function(data) {
$.each(data, function(arrayID,group) {
$.each(group.data, function(id,val) {
arg = val[0].replace(/Date.UTC\((.*?)\)/, '$1').split(',');
var timestamp = Date.UTC.apply( null , arg );
date=new Date(timestamp);
data[arrayID].data[id][0] = timestamp;
});
});
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Our PHP Script gives us this JSON:
[{"name":"Google Rank","data":[["Date.UTC(2013,04,05)","23"],["Date.UTC(2013,04,04)","23"],["Date.UTC(2013,04,03)","22"],["Date.UTC(2013,04,02)","24"],["Date.UTC(2013,04,01)","26"],["Date.UTC(2013,03,31)","24"],["Date.UTC(2013,03,30)","24"],["Date.UTC(2013,03,29)","25"],["Date.UTC(2013,03,28)","25"],["Date.UTC(2013,03,27)","25"],["Date.UTC(2013,03,26)","26"],["Date.UTC(2013,03,25)","25"],["Date.UTC(2013,03,24)","24"],["Date.UTC(2013,03,23)","-"],["Date.UTC(2013,03,22)","10"],["Date.UTC(2013,03,21)","10"],["Date.UTC(2013,03,20)","10"],["Date.UTC(2013,03,19)","10"],["Date.UTC(2013,03,18)","10"],["Date.UTC(2013,03,17)","10"],["Date.UTC(2013,03,16)","9"],["Date.UTC(2013,03,15)","9"],["Date.UTC(2013,03,14)","9"],["Date.UTC(2013,03,13)","9"],["Date.UTC(2013,03,12)","9"]],"visible":"true","pointInterval":"86400000","showInLegend":"false"},{"name":"Bing Rank","data":["Date.UTC(2013,2,9)",9],"visible":"true","pointInterval":"86400000","showInLegend":"false"}]
Note the JSON data represents numbers as strings which could be a problem.
PHP Code which generates the JSON data:
$googledata = array();
while($gkdata = mysql_fetch_assoc($keywordquery)){
$explodedate = explode("-", $gkdata['date']);
$year = $explodedate[0];
$month = $explodedate[1];
$day = $explodedate[2];
$googledata[] = array(
"".$year.",".$month.",".$day."",
$gkdata['grank'] //$gkdata['grank'] should be a number, but is sometimes a dash so it's cast to an accommodating datatype: string.
);
}
$chartdata = array(
array(
"name" => 'Google Rank',
"data" => $googledata,
"visible" => 'true',
"pointInterval" => '86400000',
"showInLegend" => 'false',
),
array(
"name" => 'Bing Rank',
"data" => array(
'Date.UTC(2013,2,9)',
9
),
"visible" => 'true',
"pointInterval" => '86400000',
"showInLegend" => 'false',
)
);
The Highcharts won't display anything other than the chart itself with no data. The Date.UTC(2013,03,12) is supposed to go on the X-Axis & the number next to it is supposed to be the rank number. Can anyone see what is wrong?
The chart takes data as [x,y]. You just need to reverse the order of your data to ['value',datestamp'] if you want the date to be on the y axis.
Edit:
I am not sure from the text what the problem you are having is, but one problem that will arise from your code is that your number data values are being returned as strings, in quotes.
You will need to cast them as integers in your php before json encoding in order for them to come through unquoted, as integers.
You should be seeing an error from this: http://www.highcharts.com/errors/14
You are expecting $gkdata['grank'] to always return a number, it sometimes returns a dash -. The Array Object is using the datatype which best represents the data, and it chooses string. If you want to force it as int, you'll have to use a data structure that only allows integers to be put in it. Then it will puke when you try to put in a dash, which it should be doing, because how do you plot a DASH on a chart?
Had you taken off your blindfold, and looked at the error HighCharts returned to you, you would see this:
Highcharts Error #14 String value sent to series.data, expected Number
This happens if you pass in a string as a data point, for example in a setup like this:
series: [{
data: ["3", "5", "1", "6"]
}]
Highcharts expects the data values to be numbers. The most common reason for this is that data is parsed from CSV or from a XML source, and the implementer forgot to run parseFloat on the parsed value.
For performance reasons internal type casting is not performed, and only the first value is checked (since 2.3).
So fix your code to make grank always a number. HighCharts won't plot strings for performance reasons.
I have a PHP array I want to pass to my jquery (replace the test array with my php array).
Array
(
[12] => Some Text
[6] => Another text
[11] => one more text
)
Jquery:
$('#SearchUser').typeahead({
source: [
{ ID: 1, Name: 'Toronto' },
{ ID: 2, Name: 'Montreal' },
{ ID: 3, Name: 'New York' },
{ ID: 4, Name: 'Buffalo' },
{ ID: 5, Name: 'Boston' },
{ ID: 6, Name: 'Columbus' },
{ ID: 7, Name: 'Dallas' },
{ ID: 8, Name: 'Vancouver' },
{ ID: 9, Name: 'Seattle' },
{ ID: 10, Name: 'Los Angeles' }
],
display: 'Name',
val: 'ID',
itemSelected: updateID
});
So how can I set the var for "source" to my php array?
Suggestions?
As always,, you are awesome!
-Tom
How I'd done it in one of my projects was,
$.get("<?= $baseUrl ?>search/data", function (data) {
var dataObject = JSON.parse(data);
$('#q').typeahead({
'source': dataObject,
// 'items': 5
});
});
and my search controller's data method is:
echo (json_encode($arr)); // $arr is ["a","b","c"] etc. but you can have an associated array too.
Basically, the point of showing my code is to say use json
You can use json_encode function of php to conver a php array to json. Then you can use the json as javascript array.
http://www.php.net/manual/en/function.json-encode.php
I don't know how you get data from php code to javascript code, but if you print data as json, you can take it via an ajax call.
Use PHP's json_encode() function to create a string that is a valid JSON, and then read that with jQuery's $.getJSON().
Something like this:
get_array.php
$someArray = /* whatever */;
echo json_encode($someArray);
read_array.js
$.getJSON('get_array.php', function(data) {
// data now contains your array
});
Alternatively, you could do something like this:
<script type="text/javascript">
var someArray = <?php echo json_encode($someArray); ?>
</script>
If you don't want the separate files and don't mind using a global variable for it.
You can do the following:
<script type="text/javascript">
var jsArray = <?php echo json_encode($phpArray); ?>
</script>
but it is a bad practice to mix language X with language Y.
Well, take a look at my answer to this post in which you can do the following in a better way:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
Hope this helps :-)