I am beginner web developer.
My code retrieves data from php and dynamically displays it on the page.
This code get data from php.
I have this code:
let productCount = 0;
function loadProducts() {
$.ajax({
type: 'GET',
url: '/pobierz-produkt',
dataType: "text",
data: {
slug: slug,
queryString: queryString,
filterDrawer: $(".filter-drawer option:selected").val(),
filterMounting: $(".filter-mounting option:selected").val(),
filtershelfs: $(".filter-shelfs option:selected").val()
},
success: function (data) {
$('.dynamic-products').html(data);
let productCount = 5;
if (productCount == 1) $('.dynamic-products-count').html('5 produktów');
if (productCount >= 2 && productCount <= 5) $('.dynamic-products-count').html(productCount + ' produkty');
else $('.dynamic-products-count').html(productCount + ' produktów');
}
});
}
It's work fine.
This code return me:
<div class="product-card">
<div class="mt-5 w-100">
<div class="w-100 mb-3 product-card-img-box text-center text-md-left">
<a href="http://name.test/produkt/produkt-1">
<img src="http://name.test/upload/products/thumbs3/559c3b396bca9c33e6dcc32ad36bc732.jpeg" class="img-fluid">
</a>
</div>
<div class="product-card-name-box text-center text-md-left">
<a class="product-card-new-info" href="#">Nowość</a><br/>
<div class="product-card-name pt-3">
Produkt 1 tv blue
</div>
</div>
<div class="product-card-category text-center text-md-left">mini opis
</div>
</div>
</div>
<div class="product-card">
<div class="mt-5 w-100">
<div class="w-100 mb-3 product-card-img-box text-center text-md-left">
<a href="http://name.test/produkt/produkt-2">
<img src="http://name.test/upload/products/thumbs3/38ae98e033d9c2dddc7b2ca7fff9acd4.jpeg" class="img-fluid">
</a>
</div>
<div class="product-card-name-box text-center text-md-left">
<a class="product-card-new-info" href="#">Nowość</a><br/>
<div class="product-card-name pt-3">
Produkt 2
</div>
</div>
<div class="product-card-category text-center text-md-left">
</div>
</div>
</div>
<div class="product-card">
<div class="mt-5 w-100">
<div class="w-100 mb-3 product-card-img-box text-center text-md-left">
<a href="http://name.test/produkt/szafka-z-szufladami">
</a>
</div>
<div class="product-card-name-box text-center text-md-left">
<a class="product-card-new-info" href="#">Nowość</a><br/>
<div class="product-card-name pt-3">
Szafka z szufladami
</div>
</div>
<div class="product-card-category text-center text-md-left">
</div>
</div>
</div>
I need save to productCount how many "product-card" was returned from php.
How can I make it? I need count "product-card"
Please help me
If your data is pure HTML returned, you can use :
success: function (data) {
// create fake div
var $data = $('<div />').html(data);
var count = $data.find('.product-card').length;
}
Here is a fiddle : https://jsfiddle.net/hfwuznvd/
You can count the length of JSON objects using Object.keys(myObject).length;
var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}
var count = Object.keys(myObject).length;
console.log(count);
Related
I want to get the value in a single card selected by the user and post it to the backend
<div class="card-body">
<div class="swiper-container swipercards">
<div class="swiper-wrapper pb-4">
<div class="swiper-slide ">
<div class="card border-0 bg-default text-white">
<div class="card-header">
<div class="row">
<div class="col-auto">
<i class="material-icons vm text-template">credit_card</i>
</div>
<div class="col pl-0">
<h6 class="mb-1">Visa</h6>
</div>
</div>
</div>
<div class="card-body">
<h5 class="mb-0 mt-3">4444 5264 2541 26651</h5>
</div>
<div class="card-footer">
<div class="row">
<div class="col">
<p class="mb-0">26/21</p>
<p class="small ">Expiry date</p>
</div>
<div class="col-auto align-self-center text-right">
<p class="mb-0">Agnish Carvan</p>
<p class="small">Card Holder</p>
</div>
</div>
</div>
</div>
</div>
<div class="swiper-slide ">
<div class="card border-0 bg-warning text-white">
<div class="card-header">
<div class="row">
<div class="col-auto">
<i class="material-icons vm text-template">credit_card</i>
</div>
<div class="col pl-0">
<h6 class="mb-1">Maestro</h6>
</div>
</div>
</div>
<div class="card-body">
<h5 class="mb-0 mt-3">4444 5264 2541 26651</h5>
</div>
<div class="card-footer">
<div class="row">
<div class="col">
<p class="mb-0">26/21</p>
<p class="small ">Expiry date</p>
</div>
<div class="col-auto align-self-center text-right">
<p class="mb-0">Agnish Carvan</p>
<p class="small">Card Holder</p>
</div>
</div>
</div>
</div>
</div>
Welcome AegisFor. It looks like you're using Swiper.js?
According to the docs, under events, here is how you determine the selected item in the carousel:
const swiper = new Swiper('.swiper', {
// ...
});
swiper.on('slideChange', function () {
console.log('slide changed', swiper.activeIndex);
});
https://swiperjs.com/swiper-api#events
You could get the values by referring to the slide's attributes, like this:
....
<div class="swiper-wrapper pb-4" >
<div class="swiper-slide " id="card-1" data-card-number="12345">
....
When you change slides, refer to the div that matches the activeIndex of the carousel:
var activeCard = document.getElementById("card-" + swiper.activeIndex);
Now you can get the card number:
var cardNumber = activeCard.getAttribute("data-card-number")
How you send it to your backend depends on what backed you have. You might do something similar to this:
fetch('http://example.com/card?card-number=' + cardNumber)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
The documentation at https://swiperjs.com/swiper-api is quite good. Remember to read the docs thoroughly before posting to SO.
I have the following select box:
<select class="form-control select2-single" data-width="100%" name="numero_projet" id="numero_projet">
<option label=" "> </option>
#foreach($projets as $projet)
<option data-id="{{$projet->id_projet}}" value="{{$projet->id_projet}}">{{$projet->numero_projet}}</option>
#endforeach
</select>
And the following ajax code to get data :
<script>
$(document).ready(function(){
$('#numero_projet').change(function(){
var id_projet = $(this).find("option:selected").data("id");
console.log(id_projet);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url:"getProjet/"+id_projet,
type:"GET",
success:function(html){
var content = html.content;
$("div.name_casting").append(content.id_casting);
}
})
})
})
</script>
And the following controller:
public function getProjet()
{
if(request()->ajax())
{
$id_projet = request('numero_projet');
$projets_casting = Projet_Casting::where('id_projet',$id_projet)->get();
return response()->json(['projets_casting' => $projets_casting]);
}
}
And I have the following view where I should display the data that I get from controller:
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Select from Library</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#foreach($projets_casting as $projet_casting)
<div class="modal-body scroll pt-0 pb-0 mt-4 mb-4">
<div class="accordion" id="accordion">
<div class="mb-2">
<button class="btn btn-link p-0 folder-button-collapse" data-toggle="collapse"
data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<span class="icon-container">
<i class="simple-icon-arrow-down"></i>
</span>
<span class="folder-name">Castings</span>
</button>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="list disable-text-selection">
<div class="row">
<div class="col-6 mb-1 sfl-item-container casting"
data-preview-path="img/products/chocolate-cake-thumb.jpg"
data-path="img/products/chocolate-cake-thumb.jpg"
data-label="chocolate-cake-thumb.jpg">
<div class="card d-flex mb-2 p-0 media-thumb-container">
<div class="d-flex align-self-stretch">
<img src="img/products/chocolate-cake-thumb.jpg" alt="uploaded image"
class="list-media-thumbnail responsive border-0" />
</div>
<div class="d-flex flex-grow-1 min-width-zero">
<div
class="card-body pr-1 pt-2 pb-2 align-self-center d-flex min-width-zero">
<div class="w-100">
<p class="truncate mb-0">{{$projet_casting->id_casting}}</p>
</div>
</div>
<div
class="custom-control custom-checkbox pl-1 pr-1 align-self-center">
<label class="custom-control custom-checkbox mb-0">
<input type="checkbox" class="custom-control-input">
<span class="custom-control-label"></span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
<div class="modal-footer">
<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Annuler</button>
<button type="button" class="btn btn-primary sfl-submit">Selectionner</button>
</div>
</div>
</div>
It should display in this div the id_casting of each projects
<div class="w-100 name_casting">
<p class="truncate mb-0">ok</p>
</div>
But I get the following error:
Uncaught TypeError: Cannot read property 'id_casting' of undefined
What is wrong with my code?
Update
I have the following HTML in my view:
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="list disable-text-selection">
<div class="row">
<div class="col-6 mb-1 sfl-item-container casting"
data-preview-path="img/products/chocolate-cake-thumb.jpg"
data-path="img/products/chocolate-cake-thumb.jpg"
data-label="chocolate-cake-thumb.jpg">
<div class="card d-flex mb-2 p-0 media-thumb-container casting2">
<div class="d-flex align-self-stretch">
<img src="img/products/chocolate-cake-thumb.jpg" alt="uploaded image"
class="list-media-thumbnail responsive border-0" />
</div>
<div class="d-flex flex-grow-1 min-width-zero">
<div
class="card-body pr-1 pt-2 pb-2 align-self-center d-flex min-width-zero">
<div class="w-100 castings">
<p class="truncate mb-0">OK</p>
</div>
</div>
<div
class="custom-control custom-checkbox pl-1 pr-1 align-self-center">
<label class="custom-control custom-checkbox mb-0">
<input type="checkbox" class="custom-control-input">
<span class="custom-control-label"></span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And I'm trying the following script:
<script>
$(document).ready(function(){
$('#numero_projet').change(function(){
var id_projet = $(this).find("option:selected").data("id");
console.log(id_projet);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url:"getProjet/"+id_projet,
type:"GET",
dataType:"json",
success:function(json){
renderTemplate(json)
}
});
function renderTemplate(json) {
var content = ` <div">
<p class="truncate mb-0">${json.id_casting}</p>
</div>`;
$("div.name_casting").append(content);
}
})
})
</script>
But I have nothing. I have always OK and I have no error!
UPDATE2
Now I can get the data that I want, but I get multiple rows in the same time so I should having multiple divs in my HTML.
I'm getting the following result:
While I shoult get the 18 in a div and 19 in other div and not in the same place.
Analogous to #professor's answer:
Use the JSON (recommended)The Controller doesn't have to be modifiedIn your blade/JavaScript, change the following:
$.ajax({
url:"getProjet/"+id_projet,
type:"GET",
dataType:"json",
success:function(json){
renderTemplate(json)
}
});
function renderTemplate(json) {
var content = `<div>
${json.castings.map((casting) => casting.id_projet)}
</div>`;
$("div.name_casting").append(content);
}
Use the HTMLThe blade view and JavaScriptIn your controller, change the following:
public function getProjet()
{
if(request()->ajax())
{
$id_projet = request('numero_projet');
$projets_casting = Projet_Casting::where('id_projet',$id_projet)->get();
return view('your-view', ['projets_casting' => $projets_casting]);
}
}
I am new to javascript and HTML. I developed website using node + express backend and using bootstrap + html + JS in front end. I have created few cards using BS4. It looks like following
Code:
<section id="cards">
<div class="container">
<div class="card-deck text-center">
<div class="card shadow-sm" id="mainCards">
<div class="card-header" id="mainCardHeader">
<h4 class="my-0 font-weight-normal">Total Cases</h4>
</div>
<div class="card-body">
<h1 class="card-title pricing-card-title"><%= areaTotal%></h1>
</div>
</div>
<div class="card shadow-sm" id="mainCards">
<div class="card-header" id="mainCardHeader">
<h4 class="my-0 font-weight-normal">Last 30 days</h4>
</div>
<div class="card-body">
<h1 class="card-title pricing-card-title"><%= arealast30%></h1>
</div>
</div>
<div class="card shadow-sm" id="mainCards">
<div class="card-header" id="mainCardHeader">
<h4 class="my-0 font-weight-normal">Last 7 days</h4>
</div>
<div class="card-body">
<h1 class="card-title pricing-card-title"><%= arealast7%></h1>
</div>
</div>
<div class="card shadow-sm" id="mainCards">
<div class="card-header" id="mainCardHeader">
<h4 class="my-0 font-weight-normal">Growth</h4>
</div>
<div class="card-body">
<h1 class="card-title pricing-card-title"><%= areaR%></h1>
</div>
</div>
<div class="card shadow-sm" id="mainCards">
<div class="card-header" id="mainCardHeader">
<h4 class="my-0 font-weight-normal">Deaths</h4>
</div>
<div class="card-body">
<h1 class="card-title pricing-card-title"><%= areaDeaths%></h1>
</div>
</div>
</div>
</div>
</section>
I want to add one more card if count>0. I have created external div before 5th card and it is working fine with following script.
var deathCount = <%- areaDeaths%>;
if (deathCount == 0){
document.getElementById("divDeath").style.display = "none";
};
However new card is not aligned correctly. Is it anyway I can make 5th element of such id disappear without harming alignment of these cards.
tried so far:
var deathCount = <%- areaDeaths%>;
if (deathCount == 0){
var elements = document.getElementById("mainCards").children;
elements.item(4).style.display = "none";
};
I have two content which are :
<div class="card text-center">
<div class="card-header">
<h5 >Prime</h5>
</div>
<div class="card-body">
<h2 id="Prime_id" class="card-title"></h2>
</div>
</div>
<div class="card text-center">
<div class="card-header">
<h5 >Benif</h5>
</div>
<div class="card-body">
<h2 id="benif_id" class="card-title"></h2>
</div>
</div>
<div class="card text-center">
<div class="card-header">
<h5 >total</h5>
</div>
<div class="card-body">
<h2 id="total_id" class="card-title"></h2>
</div>
</div>
Every content have this example of value :
<script>
console.log($("#benif_id").html()); //11.578.351 $
console.log($("#Prime_id").html()); //5.877.210 $
</script>
I want to do $("#Total_id") = $("#benif_id") + $("#Prime_id") but it's not work.
I was doing like this :
<script>
$("#total_id").text(parseFloat($("#benif_id").html()) + parseFloat($("#Prime_id").html()) + '$');
</script>
instead of
$("#total_id") = 17,455,561 $
You have to use .text() to get and set the value from/to the respective elements. You also have to convert the values to Number() before adding them. You also have to replace() the $ with empty string so that it no longer remains in the text.
var benif = $("#benif_id").text().replace('$', '');
var prime = $("#Prime_id").text().replace('$', '');
$("#Total_id").text(Number(benif) + Number(prime) + ' $');
Try this:
$("#total_id").text((
parseFloat($("#benif_id").html().split('.').join("")) +
parseFloat($("#Prime_id").html().split('.').join(""))) + '$')
removing the dots when parsing the number
Maybe what you're looking for:
var benif = $("#benif_id").text().replace(/[.\s$]/g, '');
var prime = $("#Prime_id").text().replace(/[.\s$]/g, '');
$("#Total_id").text((+benif + +prime) + ' $');
try this
$("#benif_id").html('11.578.351 $'); //11.578.351 $
$("#Prime_id").html('5.877.210 $'); //5.877.210 $
var Benif=$("#benif_id").html().replace(/\./g,'').replace('$','');
var Prime=$("#Prime_id").html().replace(/\./g,'').replace('$','');
var total=+Benif + + Prime;
//alert(total.toLocaleString())
$("#total_id").text(total.toLocaleString() + ' $');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div class="card text-center">
<div class="card-header">
<h5 >Prime</h5>
</div>
<div class="card-body">
<h2 id="Prime_id" class="card-title"></h2>
</div>
</div>
<div class="card text-center">
<div class="card-header">
<h5 >Benif</h5>
</div>
<div class="card-body">
<h2 id="benif_id" class="card-title"></h2>
</div>
</div>
<div class="card text-center">
<div class="card-header">
<h5 >total</h5>
</div>
<div class="card-body">
<h2 id="total_id" class="card-title"></h2>
</div>
</div>
I am deleting data from array and trying to update the view but it is not working.
async deleteProduct(e) {
try {
const data = await this.rest.get(environment.apiUrl + `/api/seller/products/delete/?id=${e.target.id}`);
data['success'] ? this.products = (this.products.filter(e => e != (data['products'].id))) : this.data.error(data['message']);
} catch (error) {
this.data.error(error['message']);
}
}
Html:
<section id="myProducts">
<div class="container p-5">
<app-message></app-message>
<div *ngIf="!products" class="m-auto">
<h1 class="text-center display-3 mt-5">
<i class="fa fa-spinner fa-spin"></i>
</h1>
</div>
<h3 *ngIf="products && !products.length" class="display-2 text-center mt-5">My Products is Empty</h3>
<div *ngIf="products && products.length" class="row">
<div class="col">
<h4 class="display-4">My Products</h4>
<div class="row">
<div class="offset-10 col-2 d-none d-md-block">
<p>
<small class="text-muted">Price</small>
</p>
</div>
</div>
<hr class="mt-0">
<div *ngFor="let product of products" class="product">
<div class="row">
<div class="col-4 col-md-2">
<a routerLink="/product/{{ product.id }}">
<img src="{{ product.image }}" alt="image" class="img-fluid img-thumbnail">
</a>
</div>
<div class="col-5 col-md-8">
<h5>
<a routerLink="/product/{{ product.id }}">{{ product.title }}</a>
<p class="m-0">
<small class="text-muted">{{ product.category.name }}</small>
</p>
</h5>
</div>
<div class="col-2">
<h6 class="font-weight-bold text-danger" >{{ product.price | currency : 'INR' }}</h6>
</div>
<div class="col-2">
<button type="button" class="btn btn-info" id="{{product.id}}" (click)="editProduct($event)" [disabled]="btnDisabled">Edit</button>
</div>
<div class="col-2">
<button type="button" class="btn btn-info" id="{{product.id}}" (click)="deleteProduct($event)" [disabled]="btnDisabled">Delete</button>
</div>
</div>
<hr>
</div>
</div>
</div>
</div>
</section>
After deleting the item from array, I am trying to update the object like this:
this.products = (this.products.filter(e => e != (data['products'].id)))
It seems so that your view does not check the changes of your products array.
So I would say trigger it manually:
InjectChangeDetectorRef to trigger change detection manually.
constructor(private cd: ChangeDetectorRef){....}
And in your method call this.cd.detectChanges():
async deleteProduct(e) {
...
data['success'] ? this.products = (this.products.filter(e => e != (data['products'].id))) : this.data.error(data['message']);
this.cd.detectChanges();
...
}
you are comparing e to != e['products'].id ..
it is not true.
i think you should be checking the variable which holds the id in your "e"
which means
e.id != ...or something like so.
I Hope it is working.