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.
Related
I have the following Laravel 6.x collection output when I run first() on that particular Model from a table called workflow_conflicts. As you can see the conflicts column is a JSON column and has data stored in this manner below.
Models\WorkflowConflict {
id: 2190,
created_at: "2022-02-10 12:18:28",
updated_at: "2022-02-10 12:22:36",
action: "approved",
conflicts: "[{"text": "validatorword 1218" "word": "validatorword", "indicies": {"end": 13, "start": 0}, "workflow_id": 4334}]",
user: Models\User {
id: 17843,
suspended: 0,
},
}
I am trying to figure out how would I use the Laravel Eloquent (I am using Tinker) how would I perform a search on the conflicts json values such as the values from text and word.
For instance - the following below would return the object fine in Tinker, but I am unsure how to perform a similar search on the conflicts row which is JSON data.
WorkflowConflict::where('action', 'approved')->first();
-- Expected result from within Tinker --
WorkflowConflict::where('conflicts->text', 'validatorword 1218')->first();
=> Models\WorkflowConflict {
id: 2190,
created_at: "2022-02-10 12:18:28",
updated_at: "2022-02-10 12:22:36",
action: "approved",
conflicts: "[{"text": "validatorword 1218" "word": "validatorword", "indicies": {"end": 13, "start": 0}, "workflow_id": 4334}]",
user: Models\User {
id: 17843,
suspended: 0,
},
}
-- Actual result from within Tinker --
WorkflowConflict::where('conflicts->text', 'validatorword 1218')->first();
=> null
TLDR - trying to search using the JSON column values in Laravel
Since your data is wrapped by an array, you could use a whereRaw:
WorkflowConflict::whereRaw('json_contains(conflicts, json_object("text", "validatorword 1218"))')->first();
I'm a React Native beginner, please excuse basic questions. I'm having trouble handling json returned from PHP in react native using axios get.
My php returns (have tried both with and without headers part, and also tried with/without json_encode):
<?php
$json ="[{
id: 1,
title: 'List Item One',
description: 'test1'
},
{
id: 2,
title: 'List Item Two',
description: 'test2'
}]";
header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
My react native function is below (with the part I'm trying to get to work commented out)
const [messages, setMessages] = useState([]);
useEffect(() => {
loadMessages();
}, []);
const loadMessages = async () => {
let res = await axios.get('https://example.com/test_messages.php');
//setMessages(res.data);
console.log(res.data);
}
return (
<Screen style={styles.screen}>
<FlatList
data={messages}
keyExtractor={message => message.id.toString()}
renderItem={({item}) => (
The console.log seems to work and returns:
[{
id: 1,
title: 'List Item One',
description: 'test1'
},
{
id: 2,
title: 'List Item Two',
description: 'test2'
}]
but when I try to use the commented part instead, I get this error:
"undefined is not an object ('evaluating message.id.toString')"
It seems to just be formatting the output because the console.log seems fine. Further, when I hard code the array into a variable and use it in the useState function, it works fine also.
The format of this json maybe incorrect, you can check it at https://jsonlint.com/. The correct format should be like the output of JSON.stringify below
I need to iterate through data that get via JSON with this code:
setInterval(function() {
console.log("running");
$.ajax({
type : 'get',
url : 'data.txt',
dataType : 'json',
success : function(response) {
console.log(response.bookings) // returns undefined
$.each(response.bookings, function(index, booking) {
sc.status(booking.seat_id, 'unavailable');
console.log(booking.seat_id); // returns nothing
});
}
});
}, 3000); //every 3 seconds
The data is currently formatted like this:
[{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}]
But that doesn't seem to be working. What is the correct format that I need to use? I tried a ton of options but can't get it working.
UPDATE:
The error I now get in the console is:
jquery-1.11.0.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined
at Function.each (jquery-1.11.0.min.js:2)
at Object.success ((index):145)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
at x (jquery-1.11.0.min.js:4)
at XMLHttpRequest.b (jquery-1.11.0.min.js:4)
and line 145 is:
$.each(response.bookings, function(index, booking) {
You have options here. key value {"key":value} or {"name":john} is one way. You can do more info like "employee":{ "name":"John", "age":30, "city":"New York" }
as you said I think you are response.bookings array like this $arr = [1,2,3,4,5];.
if you iterate like below
$.each($arr,function(i,k){
console.log(i,k)
})
you will get output 0,1 1,2 2,3...
but I didn't get booking.seat_id means..? can you give us booking array format?
I finally found the solution. Thank you to everyone who helped. It's pretty simple and stupid. I only had to change the JSON response from:
[{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}]
to
{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}
Basically get rid of the []
I am unable to append the values to data tables, PHP file giving the JSON response but I am unable to append the data to the data table. I have used the following code for JSON response
GetKeyWordBids.php
array_push($ret, array("keyword"=>$keyword, "svol"=>$search_volume));
}
//print_r($ret);
echo json_encode($ret);
And Json Response:
[{
"keyword": "interventional cardiology",
"svol": 6600
},{
"keyword": "pediatric cardiology",
"svol": 5400
},{
"keyword": "cardiology jobs",
"svol": 1300
},{
"keyword": "cardiology associates",
"svol": 6600
},{
"keyword": "interventional cardiology jobs",
"svol": 880
},{
"keyword": "european society of cardiology",
"svol": 5400
},{
"keyword": "nuclear cardiology",
"svol": 1600
}],
And My Jquery Code is :
$('#specialty').change(function(){
$("#example1").dataTable().fnDestroy();
var oTable = $('#example1').dataTable({
"aaSorting": []
});
var spevalue = $("#specialty option:selected").text();
var dataString='specialty='+ spevalue;
$.ajax({
type: "POST",
url: "GetKeyWordBids.php",
data: dataString,
success: function(s){
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i]['keyword'][0],
s[i]['svol'][0]
]);
}
});
});
But I am getting the error shown below. Please let me know the changes that are required.
DataTables warning (table id = 'example1'): Requested unknown parameter '0' from the data source for row 0
The JSON parser is very strict about JSON. And then your actual recall of the data is badly formatted. So:
As per splash58's comment, make sure your dataType is JSON. In your browser's developer tools (or Firebug), look at the XHR. The tool should provide a tab for viewing the response as formatted JSON. If it doesn't, or if you saw an error on the request, it might be requested with bad headers, or returned with the wrong type.
The trailing comma might be ignored by a JavaScript interpreter in general, but the JSON parser is strict and won't like it. A quick way of double-checking your JSON formatting is to fire it into JSONLint.com to see if it validates. The one you supply above does not until you remove the comma at the end.
I assume you want the full "keyword" and "svol". The extra [0] is digging into the string and returning the first character. You're going too deep into the data! What you want is s[i]['keyword'] (or s[i].keyword) and s[i]['svol'] (or s[i].svol) per this fiddle: http://jsfiddle.net/v07tvuq8/
I'm not really sure that the combination of fnClearTable and fnAddData are what you are looking for. The DataTables API allows you to specify what each column should do at initialization time, and thereafter you should just need to call draw() on it. There shouldn't be a need for iterating over your data set.
This question already has an answer here:
parsing json error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
(1 answer)
Closed 5 years ago.
I have used Laravel Response::json to generate a JSON response.
return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem));
When I run the request, I get a valid JSON (tested in JSONLint) as a response.
But the following jQuery method fails: $.parseJSON(data)
I get the following error in FireBug:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The Response I recieve:
{
"subjects": [
{
"id": 1,
"name": "Control Systems",
"semester": 1,
"year": 3,
"branch_id": 4
},
{
"id": 2,
"name": "Analog Communications",
"semester": 1,
"year": 3,
"branch_id": 4
},
{
"id": 3,
"name": "Linear IC Applications",
"semester": 1,
"year": 3,
"branch_id": 4
},
{
"id": 4,
"name": "Antennas & Wave Propagation",
"semester": 1,
"year": 3,
"branch_id": 4
}
],
"year": 3,
"sem": 2
}
And the code where I'm trying to parse it:
$(document).ready(function() {
$('#branchAndSubjects').click(function() {
$.post('/findBranchAndSubjects', {
roll: roll,
_token: "{{csrf_token()}}"
}, function(data) {
var subjects = $.parseJSON(data);
});
});
});
If you're doing the $.parseJSON(data) in an ajax success handler Since you're doing the $.parseJSON(data) in an ajax success handler, the problem is almost certainly that jQuery has already parsed it for you. jQuery will look at the Content-Type of the response and, if it's application/json, it will parse it, and provide the parsed result to your success handler. The first thing that will happen if you pass that into $.parseJSON will be that it will get converted back to a string ("[object Object]", in your case), which $.parseJSON will then fail to parse.
Just use data as-is, it's already an object, thanks to the automatic parsing:
$(document).ready(function() {
$('#branchAndSubjects').click(function() {
$.post('/findBranchAndSubjects', {
roll: roll,
_token: "{{csrf_token()}}"
}, function(data) {
console.log(data.year); // 3
console.log(data.subjects.length); // 4
console.log(data.subjects[0].name); // Control Systems
});
});
});