Fetch data from database in Laravel 9 using Vue js 3 - mysql

I wanted to read the data from the database and display it in the app.
I'm calling it like this :
<h2 class="lowongan1" v-for="value in list_lowongan"> {{ value.title }}</h2>
<p class="descJob1" v-for="value in list_lowongan">{{ value.body }}</p>
The script
export default {
data() {
return {
'form': {
title: '',
body: '',
},
list_lowongan: []
};
},
mounted() {
console.log('on mounted');
axios.get('post/list').then((response) => {
console.log(response.data)
this.list_lowongan = response.data
}).catch((error) => {
console.log(error)
});
},
The problem is, when I call it like that, It displays all the title in the database and the body in the database tables.
How can I make it so that it only display 1 title for each h2 class ?

Use a wrapping div to hold your content and then loop over the div like so:
<div v-for="value in list_lowongan">
<h2 class="lowongan1"> {{ value.title }}</h2>
<p class="descJob1">{{ value.body }}</p>
</div>

You have two for-loops independent of each other so they'll stack by themselves
You just need one for-loop to display a list of where each title and body are together
You can form it this way:
<div v-for="value in list_lowongan">
<h2>{{ value.title }}</h2>
<p>{{ value.body }}</p>
</div>

As per your requirement, No need to use multiple v-for loops for same data iteration. Instead you can achieve that by applying v-for in a wrapper element and then prints the object values inside that wrapper element.
Live Demo :
new Vue({
el: '#app',
data: {
list_lowongan: []
},
mounted() {
this.list_lowongan = [{
title: 'Title 1',
body: 'Body 1'
}, {
title: 'Title 2',
body: 'Body 2'
}, {
title: 'Title 3',
body: 'Body 3'
}]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(value, index) in list_lowongan" :key="index">
<h2>{{ value.title }}</h2>
<p>{{ value.body }}</p>
</div>
</div>

Related

How can I display selectBox items in chips?

I want to display data in chips using selectBox, but I got a problem while displaying these items like this:
My TS:
selectedPointsForts: any[]=[];
listPointsForts: any[]=[];
SelectPointsForts() {
this.PointsFortsService.findAll().then((res) => {
this.listPointsForts= res.map(function(obj: any) {
return {
value: {
id: obj.id,
name: obj.libelle
},
label: obj.libelle
};
});
});
}
My HTML:
<p-multiSelect [options]="listPointsForts" [(ngModel)]=" selectedPointsForts" [selectionLimit]=3 [panelStyle]="{minWidth:'12em'}" [maxSelectedLabels]=2></p-multiSelect>
<p>Selected Cars: </p>
<p-chips [(ngModel)]=" selectedPointsForts" > </p-chips>
Can anyone help me to fix this problem !
You can place pTemplate in <p-chips> element to format the chip items' displayed output.
<p-chips [(ngModel)]="selectedPointsForts">
<ng-template let-item pTemplate="item">
{{ item.id }} - {{ item.name }}
</ng-template>
</p-chips>
Sample Solution on StackBlitz
Output
References
Chips (Custom Content)

Nuxt how to loop on an array and display the data properly with a v-for

I have an e-commerce site, I want to loop the nested data from json. I tried many things but couldn't find.
async fetch() {
this.post = await fetch(
`http://test.com/api.php?id=${this.$route.params.id}`
).then((res) => res.json())
}
I use like this;
<h3>{{ post.title }}</h3>
<li v-for="(index, post.sizes) in sizes" :key="index">
{{ sizes.index }}
</li>
My json Data is : "sizes": "[\"XS\",\"S\",\"M\",\"L\"]",
thanks for helping.
Having this kind of code is not really okay.
<li v-for="(size, index) in sizes" :key="index">
{{ size }}
</li>
You need to update your data to something like this
sizes: [
{ id: 1, name: "XS" },
{ id: 2, name: "S" },
{ id: 3, name: "M" },
{ id: 4, name: "L" },
]
Or even better, fetch some ids from an API and then, use it like this
<li v-for="size in sizes" :key="side.id">
{{ size.name }}
</li>
Having a mutable index is not something that you should use for :key since it's does the opposite of what is is supposed to do.
:key is essential, more info here: https://v2.vuejs.org/v2/style-guide/#Keyed-v-for-essential
Here a blog article explaining this: https://michaelnthiessen.com/understanding-the-key-attribute#dont-use-an-index-as-the-key

Laravel 8 - ajax removing first row

I'm beginner in Ajax and I'm using Laravel 8. I want to remove row that from database but when I try this code it's removing first row but it needs to remove the returned id row. How can I remove the row?
My blade is:
<div class="anime__review__item" id="testp" >
<div class="anime__review__item__pic">
<img src="<?=url('/')?>/images/avatars/{{$comment->user->photo}}" alt="">
</div>
<div class="anime__review__item__text" >
<h6><a href="{{route('getProfile', ['username'=> $comment->user->username])}}" >{{$comment->user->name }}</a></a><span >{{$comment->created_at->diffForHumans()}}</span></h6>
<p> {{$comment->comment }}</p>
<p class="card-text"><span class="icon_trash" type="button" data-id="{{ $comment->id }}" data-target="#default{{ $comment->id }}"></span></p>
</div>
</div>
My ajax is:
$(".icon_trash").click(function(event){
event.preventDefault();
var id = $(this).data("id");
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: "{{ route('deleteComments',['id' => $comment->id]) }}",
type: 'POST',
data: {
_token: "{{ csrf_token() }}",
id: id
},
success: function (){
$("#testp").remove();
},
error: function(){
alert('errorr');
},
})
}
})
});
My controller is:
public function deleteComments($id){
$deletedata= Comment::findOrFail($id);
$deletedata->delete();
if($deletedata){
return response()->json(['status'=>'testss']);
}else{
return back();
}
}
Since all divs have same ID, you have this issue. To solve, have unique IDs and unique removals as below:
Have dynamic value for div ID as:
<div class="anime__review__item" id="testp_{{ $comment->id }}">
Remove the respective ID accordingly in your ajax code as:
$("#testp_{{ $comment->id }}").remove();
This way, you correctly remove the parent div of the respective deleted comment.

PieChar inside for loop tag html django

I am facing this challenge of creating multiple pieChart plot in my html page.
I have a for loop in the page and I want to plot the data.
I just insert the script inside the loop but it doesn't work.
the code is:
{% for welTsts in WellTsTProDChart %}
<div id='{{welTsts.TestDate}}' class="container">
<div class="row">
<div class="col-lg-6">
</div></div>
<div class="col-lg-6">
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Production Tests: {{ welTsts.TestDate }} Oil {{ welTsts.TestOIL}} (m3/D)</h3>
</div>
<div class="card-body w3-light-grey solid">
<canvas id='{{welTsts.TestDate}}' style="min-height: 230px; height: 230px; max-height: 245px; max-width: 100%;"</canvas>
{% block custom_js %}
<script>
$(document).ready(function(){
//Data Set for PIE CHart
var pieData = {
labels: [
'OIl',
'Water'
],
datasets: [
{
data: [{{ welTsts.TestOIL}} , {{ welTsts.TestWtr}}],
backgroundColor : ['#00a65a', '#5088f1'],
}
]
}
var pieChartCanvas = $('#{{welTsts.TestDate}}').get(0).getContext('2d')
var pieOptions = {
maintainAspectRatio : false,
responsive : true,
}
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
var pieChart = new Chart(pieChartCanvas, {
type: 'pie',
data: pieData,
options: pieOptions
})
})
</script>
{% endblock custom_js %}
</div></div></div></div></div>
{% endfor %}
when I have just one data it doesn't know the variables (data: [{{ welTsts.TestOIL}} , {{ welTsts.TestWtr}}])
and if I set fixed number like data: [70, 30] it plot it but just one plot even if there is many plot to show as the images below. it take the last var inside the script and put it in the first element in for loop!
and after adding unique Id

Display JSON Object to front end using services in Angular2

I have been trying to display a json file having multiple arrays in it on the front-end div tag in using Services Angular2 using Typescript. Can anyone help?
Also, If anyone can help transforming this code by adding Model and Interface class would be very helpful.
Here is the code:
SERVICE
export class HttpServiceDemo{
_data: any;
private url: string = "assets/sample.json"
constructor(private http: Http){}
getMyOrder(){
//return this.http.get(this.url)
// .map((response: Response)=> response.json());
return this.http.get(this.url)
.map(res => this.http = res.json().myOrder);
}
}
component.ts
export class SimpleHTTPComponentComponent implements OnInit {
data:any;
Order_date:any;
OrderNumber: number;
P_O_Number:number;
Total: number;
Quote_Status: string;
Expiration_Date: any;
Quote_Created_On: any;
constructor(public vara: HttpServiceDemo) {
}
ngOnInit() {
//calling myorder from json
this.vara.getMyOrder().subscribe(response => {
this.data=response;
for (var myOrder in this.data)
{
console.log(myOrder, this.data[myOrder]);
this.Order_date=this.data[myOrder].Order_Date;
this.OrderNumber=this.data[myOrder].OrderNumber;
this.P_O_Number=this.data[myOrder].P_O_Number;
this.Total=this.data[myOrder].Total;
this.Quote_Status=this.data[myOrder].Quote_Status;
}
})
}
sample.json
---------------
{
"accOrder":[
{
"Order_Date": "10-sep-1981",
"OrderNumber" : "E12345",
"P_O_Number": "P12345",
"Total": "123",
"Quote_Status": "In Progress"
},
{
"Order_Date": "1-oct-1981",
"OrderNumber" : "E82398",
"P_O_Number": "P87815",
"Total": "265",
"Quote_Status": "In Progress"
},
{
"Order_Date": "21-nov-1981",
"OrderNumber" : "E52367",
"P_O_Number": "P76549",
"Total": "454",
"Quote_Status": "In Progress"
},
{
"Order_Date": "10-dec-1981",
"OrderNumber" : "E42840",
"P_O_Number": "P23632",
"total": "123",
"Quote_Status": "Completed"
}
]
}
You are saying your console.log() shows the JSON just fine ?
Then, your data is correctly fetched into your component's data attribute.
You just have to go through your attribute in your template using *ngFor directive then.
Plunkr : https://plnkr.co/edit/4IdV3OHyNFNi90KXQQHP?p=preview
template: `
<div>
<div *ngFor="let order of data.accOrder" style="border: 1px solid lightgrey; padding: 15px; margin: 5px 0;">
Order_Date : {{ order.Order_Date }} <br>
OrderNumber : {{ order.OrderNumber }} <br>
P_O_Number : {{ order.P_O_Number }} <br>
Total : {{ order.Total }} <br>
Quote_Status : {{ order.Quote_Status }} <br>
</div>
</div>
`
PS : No need for your "for" loop inside ngOnInit() , this is not how you should access the data.
You should check out the ngFor doc to learn more about it.
EDIT :
As I said in my comment below, my previous Plunker was using raw data while you use asynchronous data in your use case (it's coming from an Observable sent from your service).
To make it work then, you have to check if your component already received the data before you try to display it. For that, you need to use the *ngIf directive.
New Plunkr : https://plnkr.co/edit/W5qykrh4blplGxTyp8aC?p=preview
template: `
<div *ngIf="data; else loading">
<div *ngFor="let order of data.accOrder" style="border: 1px solid lightgrey; padding: 15px; margin: 5px 0;">
Order_Date : {{ order.Order_Date }} <br>
OrderNumber : {{ order.OrderNumber }} <br>
P_O_Number : {{ order.P_O_Number }} <br>
Total : {{ order.Total }} <br>
Quote_Status : {{ order.Quote_Status }} <br>
</div>
</div>
<ng-template #loading>Fetching the data from the webservice... Wait 3 seconds !</ng-template>
`,
You have to create a parent div to the one with your *ngFor directive. In this parent div, use the *ngIf="data" directive. Everything inside it will not be displayed until there is some data into the data attribute.
I used here an if/else syntax which appeared with Angular4. But you don't need that. That's just here to display a message while there is no data. It could be a loading spinner for example, to let the user know he has to wait.
If you don't want to use this if/else condition, you can do it without it like that :
template: `
<div *ngIf="data">
<div *ngFor="let order of data.accOrder" style="border: 1px solid lightgrey; padding: 15px; margin: 5px 0;">
Order_Date : {{ order.Order_Date }} <br>
OrderNumber : {{ order.OrderNumber }} <br>
P_O_Number : {{ order.P_O_Number }} <br>
Total : {{ order.Total }} <br>
Quote_Status : {{ order.Quote_Status }} <br>
</div>
</div>
`,
Hope this helped :)