Unable to Fetch JSON Response in VueJS - json

My goal: I'm trying to create a table in VueJS and populate it with data from a JSON file.
JSON file:
{
"users": [
{
"id_num": 1,
"name": "Max",
"date_registered": "2021-05-15"
},
{
"id_num": 2,
"name": "Sabrina",
"date_registered": "2021-07-23"
},
{
"id_num": 3,
"name": "Sasha",
"date_registered": "2021-09-02"
}
]
}
My table (located in the template section of its respective component file in VueJS):
<body>
<div class="container mt-4" id="app">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">
ID Number
</th>
<th scope="col">
Name
</th>
<th scope="col">
Date of Registration
</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id" class="user">
<td>{{ user.id_num }}</td>
<td>{{ user.name }}</td>
<td>{{ user.date_registered}}</td>
</tr>
</tbody>
</table>
</div>
</body>
My fetch call (located in the script section of the same component file as my table):
export default {
data() {
return {
users: [],
};
},
mounted() {
fetch('http://localhost:3000/users')
.then((response) => response.json())
// eslint-disable-next-line no-return-assign
.then((data) => (this.users= data))
.catch((err) => console.log(err.message));
},
};
My result when I test locally: I see the first row with the three columns of my table (ID Number, Name, Date of Registration) but that's all. There are no rows with the info from my API. When I open the console, it says Failed to load resource: net::ERR_CONNECTION_REFUSED :3000/users:1 and Failed to fetch.

Related

Passing JSON data to Laravel view without casting in the model

I have this function that fetches data from a table, paginates the data, and passes it to the view:
public function job_requests(){
$orders = DB::table('orders')
->select('id','order_data','order_status')
->paginate(5);
return view('autorepair/mechanics/job_requests',compact('orders'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
The column order_data contains data of the following format:
{
"personal_data": {
"email": "info#info.com",
"telephone_number": "0999",
"postal_address": "LON",
"car_registration": "GB BHG"
},
"inperson_diagnostic": {
"diagnostic_inspection": "67.30",
"car_wont_start_inspection": "67.30",
"plugin_diagnostic_inspection": "67.30"
},
"tyres": {
"front_wheels": 1,
"rear_wheels": 1,
"wheel_width": 45,
"wheel_profile": 1,
"wheel_rim": 1,
"speed_rating": "w",
"final_price": 90
},
"servicing_and_mot": {
"mot_with_collection_delivery": 75,
"major_service": 304.52,
"full_service": 203.45,
"interim_service": "149.70",
"vehicle_health_check": 50
},
"inspection_services": {
"premium_prepurchase_inspection": 146.38,
"standard_prepurchase_inspection": 104,
"basic_prepurchase_inspection": 86.44
},
"repairs": {
"ABS wheel speed sensor replacement": 964,
"ABS pump replacement": 712,
"Brake pedal switch replacement": 568,
"Air conditioning regas (R1234yf Gas ONLY)": 469
}
}
In my view, I have this:
#if(!$orders->isEmpty())
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Order Status</th>
<th>Order Data</th>
<th width="280px">Action</th>
</tr>
#foreach ($orders as $order)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $order->order_status }}</td>
<td>{{ $order->order_data}}</td>
<td>
<a class="btn btn-info" href="{{ url('/view_product/' . $order->id) }}">Show</a>
<a class="btn btn-primary" href="{{ url('/edit_product/' . $order->id ) }}">Accept</a>
</td>
</tr>
#endforeach
</table>
#else
<p>No orders yet.</p>
#endif
{!! $orders->links() !!}
I can display the JSON data here $order->order_data but I would like to have it decoded first. How can I pass a decoded array sent to the view and be able to keep the pagination links?
You could decode it in the view.
Depending on the format of order_data that is actually passed to the view (forgive me, I don't know off-hand how builder or eloquent retrieves jsonb type), but you can use dd() or gettype() in the view, to help identify what data type order_data is when delivered to the view):
If the content comes into the view as a string, try json_decode() on the order_data value. I think you should be able to iterate over the result of that, if that is your intent.

Laravel Vue displaying from database table result using v-for directive not correctly

I have a problem with laravel and vue about displaying the result from database table find method. What I don't quite understand is why the v-for directive parsing the json result incorrectly.
Here is the Vue code :
<template>
<table class="table table-hover">
<thead>
<tr>
<th>Class</th>
<th>Amount of Students</th>
<th>Teacher</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="classroom in classrooms" :key="classroom.id">
<td>{{ classroom.class_no }}•{{ classroom.field }}•{{ classroom.room_no }}</td>
<td>{{ classroom.amount_students }}</td>
<td>{{ classroom.teacher }}</td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data () {
return {
classrooms : {
"success": true,
"data": { "id": 1, "class_no": 1, "field": "Architecture", "room_no": 4, "amount_students": 40, "teacher": "Bobby Fisher" },
"message": "Find Classroom Detail"
}
}
}
}
</script>
The json classrooms itself is actually the result from the controller :
public function show($level)
{
$classrooms = ClassRoom::where('class_no', $level)->firstOrFail();
return $this->sendResponse($classrooms , 'Find Classroom Detail');
}
And here is screenshot of the wrong result :
The result should be only a single row
Please help me to solve this problem.
Actually, as you are iterating over the classrooms which is an object having three keys, so the for loop is iterating over each key once.
If you only want to iterate over the data key then just return the data from the backend.
You can use a v-if condition to check whether the current key contains a class_no and if yes then display the row otherwise not.
<tr v-for="classroom in classrooms" :key="classroom.id" v-if="classroom.class_no">
<td>{{ classroom.class_no }}•{{ classroom.field }}•{{ classroom.room_no }}</td>
<td>{{ classroom.amount_students }}</td>
<td>{{ classroom.teacher }}</td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
</td>
</tr>
Looking at your Vue data attribute, you want to use v-for="classroom in classrooms.data".
And if you are getting the data from API then you don't want to assign the full response to your classroom data attribute but assign response.data to classroom, so you can do
v-for="classroom in classrooms".
This will work unless your API returns data in a different format.
you can check on JsFiddle
https://jsfiddle.net/JManish/9qjvdy8n/2/
Make some changes in your classroom's data attribute.
<table class="table">
<thead>
<tr>
<th>Class</th>
<th>Amount of Students</th>
<th>Teacher</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(classroom, index) in classrooms.data" :key="index">
<td>{{ classroom.class_no }}•{{ classroom.field }}•{{ classroom.room_no }}</td>
<td>{{ classroom.amount_students }}</td>
<td>{{ classroom.teacher }}</td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
</td>
</tr>
</tbody>
</table>
new Vue({
el: '#app',
data() {
return {
classrooms: {
"success": true,
"data":[
{
"id": 1,
"class_no": 1,
"field": "Architecture",
"room_no": 4,
"amount_students": 40,
"teacher": "Bobby Fisher"
}
],
"message": "Find Classroom Detail"
}
}
}
})
Hope this will resolve your parsing issue.

Filling a table with JSON data

I am taking mmy first steps in Angular and was about to try populating a table with data stored in a JSON file. Facing a bit of an odd/unexpected situation there as the table doesn't look exactly how I expected it to look. First things first.
Table code:
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Transfers</th>
<th>Tools</th>
</tr>
</thead>
<tbody>
<tr *ngFor = "let data of linksArray">
<td>{{ data.Transfers}}</td>
<td>{{ data.Tools}}</td>
</tr>
</tbody>
</table>
What I would like to achieve is that the columns Transfers and Tools get filled with data that uses the corresponding keywords in my JSON file. And here it is
[{"Type":"Transfers","Name":"1","Hyperlink":"#"}, {"Type":"Transfers","Name":"2","Hyperlink":"#"},
{"Type":"Tools","Name":"1","Hyperlink":"#"}, {"Type":"Tools","Name":"2","Hyperlink":"#"}]
The array gets loaded by using this in my .ts file
this.http.get('../../assets/templatefiles/links.json').subscribe(data => {this.linksArray = data as
any [];
console.log(this.linksArray);
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
So far all looks good, I see the array popping up in console, but then look at the table and am confused
I would have expected the entries in the 2nd column to start in the first cell. Instead they start in the 3rd? What am I missing here? Been marveling for quite a while now :)
https://stackblitz.com/edit/angular-ivy-hvcyfq
To get this
Transfers Tools
1 10
2 20
You want code roughly like this
<hello name="{{ name }}"></hello>
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Transfers</th>
<th>Tools</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of linksArray">
<td>{{data.Transfers.Name}}</td>
<td>{{data.Tools.Name}}</td>
</tr>
</tbody>
</table>
And, this is the main bit, json roughly like this
linksArray = [
{
Transfers: {
Name:"1",
Hyperlink:"#"
},
Tools: {
Name:"10",
Hyperlink:"#"
}
},
{
Transfers: {
Name:"2",
Hyperlink:"#"
},
Tools: {
Name:"20",
Hyperlink:"#"
}
},
Your existing json looks like this, where the '{' represents one row
[
{
"Type":"Transfers",
"Name":"1",
"Hyperlink":"#"
},
{
"Type":"Transfers",
"Name":"2",
"Hyperlink":"#"
},
{
"Type":"Tools",
"Name":"1",
"Hyperlink":"#"
},
{
"Type":"Tools",
"Name":"2",
"Hyperlink":"#"
}
]

I'm getting some errors while passing data to the frontend

I'm getting some errors while passing data to the frontend, but when I return this $order then it shows a JSON data like this
[
{
"id": 1,
"customer_id": 3446467182106354,
"products": {
"1": {
"'name'": "Soap",
"'quantity'": "1"
},
"2": {
"'name'": "Shampoo",
"'quantity'": "1"
}
},
"total_amount": 798,
"status": "pending",
"created_at": "2020-10-21T08:51:15.000000Z",
"updated_at": "2020-10-21T08:51:15.000000Z"
}
]
But when I pass It to the front end it says like this
Property [products] does not exist on this collection instance. (View: C:\xampp\htdocs\blog\resources\views\customer\orders.blade.php)
by the way I've a json data in my database
looking at the json data u have mentioned in the question, Products is array of products and its in side main array.
you can access products this way...
make another foreach loop for products
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Products</th>
<th scope="col">Total</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
#foreach ($orders as $order)
<tr>
#foreach{{$order->products as $product}}
<th>{{ $product->name }}</th>
#endforeach
<td>{{ $order->total }}</td>
<td>{{ $order->status }}</td>
</tr>
#endforeach
</tbody>
you need to loop over you cannot print collcetion so you need to update your controller and blade file like this
Controller
public function customerOrders($id)
{
$orders = Order::where('customer_id', $id)->get();
return view('customer.orders', compact('orders'));
}
blade
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Products</th>
<th scope="col">Total</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
#foreach ($orders as $order)
<tr>
<th>
#foreach ($order->products as $product)
{{ $product['name'] }}
#endforeach
</th>
<td>{{ $order->total }}</td>
<td>{{ $order->status }}</td>
</tr>
#endforeach
</tbody>
</table>
like this you will get all the data
Before using this data you should use json_decode() function

Cannot print a table with *ngFor from a json

This particular Json does not have the key of each element in the arrays, I managed to make this work with other Jsons which bring the element keys and use those keys in the {{data.key}} to print with *ngFor.
I tried more than 25 solutions in stackoverflow but it seems that my case is unique, no one else uses a JSON without keys/labels to create a table.
This is my Json:
{
"data": {
"spnf": {
"anios": [
"2018-Q4",
"2018-Q4"
],
"titulos": [
"Ingresos Totales",
"Balance Total"
],
"anioactual": [
3183,
-837
],
"anioanterior": [
3672,
1549
]
},
"gob_central": {
"anios": [
"2018-Q4",
"2018-Q4"
],
"titulos": [
"Ingresos Totales",
"Balance Total"
],
"anioactual": [
3183,
-837
],
"anioanterior": [
3672,
1549
]
}
}
}
This is my balances.ts:
{
this.loader.present().then(() => {
this.finanzaService.getBalances2()
.subscribe((result) => {
this.dataRequest = result;
this.setData();
// Disable Loader
this.loader.dismiss();
}, (err) => {
"error blah blah"
}
);
});
}
public setData(tipo: string = 'spnf') {
if (tipo == 'spnf') {
this.dataResumen = _.clone(this.dataRequest.spnf);
} else {
this.dataResumen = _.clone(this.dataRequest.gob_central);
}
}
This is my finanzapublica.service.ts:
public getBalances2(): Observable<any>{
const url = `${this.apiURL}/balances_fiscales/balances_datos2.json`;
return this.http.get(url, this.options)
.map((res: Response) => res.json().data);
}
This is my balances.html, as soon as I try this.dataResumen, the app breaks and throws error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
<table *ngIf="dataRequest">
<thead>
<tr>
<td class="border" text-center>Rubro</td>
<td class="border" *ngFor="let data of this.dataResumen.anios" text-center>{{ data }}</td> <!--this works-->
</tr>
</thead>
<tbody>
<tr *ngFor="let data of this.dataResumen"><!--this doesn't work-->
<td class="border" text-center>{{data.titulos}}</td>
<td class="border" text-center>{{data.anioactual}}</td>
<td class="border" text-center>{{data.anioanterior}}</td>
</tr>
</tbody>
</table>
This is the error:
Cannot find a differ supporting object '{
"anios": [
"2018-Q4",
"2018-Q4"
],
"titulos": [
"Ingresos Totales",
"Balance Total"
],
"anioactual": [
3183,
-837
],
"anioanterior": [
3672,
1549
]
}' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
The result I wanted is like:
Rubros 2018-Q4 2018-Q4
Ingresos Totales 3183 3672
Balance Total -837 1549
<table>
<thead>
<tr>
<td class="border" text-center>Rubro</td>
<td class="border" *ngFor="let data of dataResumen?.anios" text-center>{{ data }}</td> <!--this works-->
</tr>
</thead>
<tbody>
<tr *ngFor="let data of dataResumen.titulos; let i=index;">
{{data}}
<td>{{dataResumen.anioactual[i]}}</td>
<td>{{dataResumen.anioanterior[i]}}</td>
</tr>
</tbody>
</table>