I am trying to figure out how to organise and append html dynamically from Json.
the keys of the Json data are Image, id, link, ajaxlink. My html looks like this:
<div class="col s12 m6 l3">
<div class="card z-depth-4">
<div class="card-image waves-effect waves-block waves-light" style="height:350px">
<a href="#Url.Action("Movie", "Home", new { id ="", title = "", year="" })">
<img class="activat" src="">
</a>
</div>
<div class="card-content blue-grey darken-4">
<span class="card-title activator grey-text text-darken-1"><a class="a-title truncate" style="color:inherit">title</a><i class="material-icons right" onclick="loadDoc('id', 'ajax')">more_vert</i></span>
<p>Report broken link</p>
</div>
<div class="card-reveal blue-grey darken-4">
<span class="card-title grey-text text-darken-1 title-wrap"><i class="material-icons right">close</i></span>
<div id=""></div>
</div>
</div>
</div>
and my jquery is embarrassing
$(".tab a").click(function (e) {
var url = "";
var fillentry = $('#fillentry');
var test = $(e.target).text();
if (test === 'Top Viewed Today') {
var url = "http://topview-today";
} else if (test === 'Most Favorite') {
var url = "https://top-favorite";
} else if (test === 'Top Rating') {
var url = 'https://top-rating';
} else if(test === 'Top show'){
url = 'https://top-show';
}
else {
throw new Error('kill execution');
}
$.ajax({
url: '../../Home/tabcontent?=' + url,
type: "GET",
success: function (response) {
$.each($.parseJSON(response), function (i, item) {
fillentry.empty();
if (item.length) {
var fill1 = '<div class="card z- depth - 4" id="fill1">'+ '<div class="card-image waves-effect waves-block waves-light" style="height:350px">'+
'< a href= "#Url.Action("Movie", "Home", new { id ="", title = "", year="" })">' +
'<img class="activat" src="' + item.image + '">' +
'</a>'+
'</div >'
+ '<div class="card-content blue-grey darken-4">' +
'<span class="card-title activator grey-text text-darken-1">' + '<a class="a-title truncate" style="color:inherit">title</a>' + '<i class="material-icons right" onclick="loadDoc(' + item.id + ',' + item.ajax+ ')">more_vert</i>'+'</span>'
+'<p>'+'Report broken link'+'</p>'
+'</div>'+
'<div class="card-reveal blue-grey darken-4">'
+'<span class="card-title grey-text text-darken-1 title-wrap"><i class="material-icons right">close</i>'+'</span>'+
'<div id="">'+'</div>'+
'</div>' + '</div>';
fillentry.append(fill1);
}
});
I need to interate through the Json object and bind the data to the grid.
Related
Try catch doesn't work on my code, I'm using a library to create pagination called "pagination.js", and when my server doesn't return any item, the library return an error:
Uncaught Error: Pagination: dataSource.items is undefined.
I want to give a message on the screen when there's no item on database
try {
$('#url-list').pagination({
dataSource: 'get_data.php?action=all-urls',
locator: 'items',
totalNumberLocator: function(response) {
return response.totalRows;
},
pageSize: 10,
className: 'paginationjs-theme-blue paginationjs-big',
afterPreviousOnClick: function() {
window.location = "dashboard.php#urls";
},
afterPageOnClick: function() {
window.location = "dashboard.php#urls";
},
afterNextOnClick: function() {
window.location = "dashboard.php#urls";
},
callback: function(data) {
var paginationWrapper = $('#url-list');
var dataContainer = $('.url-list-wrapper', paginationWrapper);
var html = '<ul class="p-0">';
$.each(data, function(index, items) {
html += '<div class="url-wrapper p-4 mb-4"><div class="is-flex is-justify-content-space-between"><p class="url-wrapper-limit is-size-5">' + items.long_url + '</p><p class="ml-3 is-size-5">' + items.date + '</p></div><hr class="url-wrapper-divider"><div class="is-flex is-justify-content-space-between mb-4">dcsr.link/' + items.url_id + '<div class="is-flex is-align-items-center"><span class="tag is-primary mr-1 has-text-weight-bold is-size-6">' + items.clicks + '</span><p class="is-size-5">Clicks</p></div></div><div class="url-wrapper-footer is-flex is-justify-content-space-between"><div><button class="button is-primary mr-1"><i class="fa-solid fa-copy"></i></button><button class="button is-primary mr-1"><i class="fa-solid fa-pen-to-square"></i></button><button class="button is-primary mr-1"><i class="fa-solid fa-qrcode"></i></button><button class="button is-danger mr-1"><i class="fa-solid fa-trash"></i></button></div><div><button class="button is-primary"><i class="fa-solid fa-chart-line mr-2"></i><p>Stats</p></button></div></div></div>';
});
html += '</ul>';
dataContainer.html(html);
}
});
} catch (error) {
alert('Server didn'
t
return any item!')
}
Instead of try/catch check data.length with if/else condition.
Some thing like this inside callback function.
callback: function(data) {
if (data.length > 0) {
var paginationWrapper = $('#url-list');
var dataContainer = $('.url-list-wrapper', paginationWrapper);
var html = '<ul class="p-0">';
$.each(data, function(index, items) {
html += '<div class="url-wrapper p-4 mb-4"><div class="is-flex is-justify-content-space-between"><p class="url-wrapper-limit is-size-5">' + items.long_url + '</p><p class="ml-3 is-size-5">' + items.date + '</p></div><hr class="url-wrapper-divider"><div class="is-flex is-justify-content-space-between mb-4">dcsr.link/' + items.url_id + '<div class="is-flex is-align-items-center"><span class="tag is-primary mr-1 has-text-weight-bold is-size-6">' + items.clicks + '</span><p class="is-size-5">Clicks</p></div></div><div class="url-wrapper-footer is-flex is-justify-content-space-between"><div><button class="button is-primary mr-1"><i class="fa-solid fa-copy"></i></button><button class="button is-primary mr-1"><i class="fa-solid fa-pen-to-square"></i></button><button class="button is-primary mr-1"><i class="fa-solid fa-qrcode"></i></button><button class="button is-danger mr-1"><i class="fa-solid fa-trash"></i></button></div><div><button class="button is-primary"><i class="fa-solid fa-chart-line mr-2"></i><p>Stats</p></button></div></div></div>';
});
html += '</ul>';
dataContainer.html(html);
} else {
alert('Server didn\'t return any item!')
}
}
I am trying to pass multiple parameters in a 'onclick' but it is not working and JS gave me headaches.
When clicking the 'div' and going to agregarADetalleMenu gives me this error:
SyntaxError: missing ) after argument list
function LlenarTableMenu(data) {
$('#cards-productos').empty();
$.each(data, function(i, val) {
var block2 = '<div class="col-4 col-md-6" onclick="agregarADetalleMenu(' + val.id + ', ' + val.name + ', ' + val.price + ')">' +
'<figure class="card card-product"> ' +
'<div class="img-wrap">' +
' <img src="' + val.imagen + '">' +
#* '<center><a class="btn-overlay" href="#"><i class="fa fa-plus-circle"></i> AGREGAR </a></center>' + *# '</div>' +
'<figcaption class="info-wrap">' +
'' + val.name + '' +
'<div class="action-wrap"> ' +
'<div class="price-wrap h5">' +
#* '<span class="price-new">' + val.price.toFixed(2) + '</span>' + *# '<span style="display: none;" class="catid">' + val.id + '</span>' +
'</div>' +
'</div>' +
'</figcaption> ' +
'</figure> ' +
'</div>';
$("#cards-productos").append(block2);
});
}
Do you mean this?
Note I wrapped the function values in quotes - you nested your quotes
function LlenarTableMenu(data) {
$('#cards-productos').html(
data.map(val => `<div class="col-4 col-md-6" onclick="agregarADetalleMenu('${val.id}','${val.name}',${val.price})">
<figure class="card card-product">
<div class="img-wrap">
<img src="${val.imagen}">
<center><a class="btn-overlay" href="#"><i class="fa fa-plus-circle"></i> AGREGAR </a></center>
</div>
<figcaption class="info-wrap">
${val.name}
<div class="action-wrap">
<div class="price-wrap h5">
<span class="price-new">${val.price.toFixed(2)}</span>
<span style="display: none;" class="catid">${val.id}</span>
</div>
</div>
</figcaption>
</figure>
</div>`).join("")
);
}
This is better
function LlenarTableMenu(data) {
$('#cards-productos').html(
data.map(val => `<div class="agregar col-4 col-md-6" data-id="${val.id}" data-name="${val.name}" data-price="${val.price}">
<figure class="card card-product">
<div class="img-wrap">
<img src="${val.imagen}">
<center><a class="btn-overlay" href="#"><i class="fa fa-plus-circle"></i> AGREGAR </a></center>
</div>
<figcaption class="info-wrap">
${val.name}
<div class="action-wrap">
<div class="price-wrap h5">
<span class="price-new">${val.price.toFixed(2)}</span>
<span style="display: none;" class="catid">${val.id}</span>
</div>
</div>
</figcaption>
</figure>
</div>`).join("")
);
}
and then have
$('#cards-productos').on("click",".agregar",function() {
agregarADetalleMenu(this.dataset.id,this.dataset.val,this.dataset.price)
})
You're missing quotes around the values being passed in to the function. Because you already used single and double quotes in your string, you can use escaped single (or double) quotes as follows:
onclick="agregarADetalleMenu(\'' + val.id + '\', \'' + val.name + '\', \'' + val.price + '\')"
I have a homepage where there is a menu with some categories and below there are the latest posts:
<ul class="Categories__Menu">
#foreach($categories->take(6) as $category)
<li class="ative">
{{$category->name}}
</li>
#endforeach
</ul>
<div class="row" id="posts">
#foreach($posts as $post)
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="{{$post->image}}" alt="Card image cap">
<h5 class="card-title">{{$post->name}}</h5>
<div class="card-footer d-flex justify-content-between align-items-center">
More
</div>
</div>
</div>
#endforeach
</div>
I want that when each category is clicked to show only the posts of that category in the homepage, but in the same homepage, not in a specific category page.
So I have this Ajax:
$(function() {
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
$('#posts').append("<p>"+postObj.name+"</p>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
});
And its working fine, but instead of show just this:
$('#posts').append("<p>"+postObj.name+"</p>");
I want to show the posts with the real html above like:
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="{{$post->image}}" alt="Card image cap">
<h5 class="card-title">{{$post->name}}</h5>
<div class="card-footer d-flex justify-content-between align-items-center">
More
</div>
</div>
</div>
So Im using like this in ajax:
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
alert(category_id);
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
//$('#posts').append("<p>"+postObj.name+"</p>");
$('#posts').append("<div class=\"col-12 col-sm-6 col-lg-4 col-xl-3 mb-4\">\n" +
" <div class=\"card box-shaddow\">\n" +
" <img class=\"card-img-top\" src=\"{{postObj.image}}\" alt=\"Card image cap\">\n" +
" <h5 class=\"card-title h6 font-weight-bold text-heading-blue\">{{postObj.name}}</h5>\n" +
" <div class=\"card-footer d-flex justify-content-between align-items-center\">\n" +
"\n" +
" More\n" +
" </div>\n" +
" </div>\n" +
" </div>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
But it appears an error:
Use of undefined constant postObj - assumed 'postObj'
Do you know why?
PostController:
public function WhereHasCategory(Request $request)
{
$posts = Post::whereHas('categories', function ($categories) use (&$request) {
$categories->where('id',$request->id);
})->get();
return response()->json($posts);
}
Route to the ajax part:
Route::get('posts/where/category/{id}','\PostController#WhereHasCategory')->name('category.posts');
Method to return the homepage view:
public function index(){
return view('home')
->with('categories', Category::orderBy('created_at', 'desc')->get())
->with('posts', Post::orderBy('created_at','desc')->take(8)->get());
}
Make sure you refer to variable in Blade template with $postObj, not postObj. I can see you use it without $, like postObj.image in your tag.
I'm new here and I'm a beginner in programming.
I need help with my weather app. I'm using metaweather api for displaying weather, but i need to display weather for multiple location.
This is how i display weather for only one city, but i dont know how to pass more cities?!
Please help!
Here it's code (HTML)
<main>
<section>
<div class="container">
<div id="main_panel">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/warszawa.jpg" alt="Warszawa">
<span id="warsaw">
<span class="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
</span>
<span class="weather">
<span class="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<span class="weather-icon"></span>
<h3 class="weather-state"></h3>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/berlin.jpg" alt="Berlin">
<span id="berlin">
<span class="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
</span>
<span class="weather">
<span class="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<h3 class="weather-state"></h3>
<span class="weather-icon"></span>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/lizbona.jpg" alt="Lizbona">
<span id="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
<span class="weather">
<span id="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<h3 class="weather-state"></h3>
<span class="weather-icon"></span>
</span>
</div>
</div>
</div>
</div>
</section>
</main>
And here it is JavaScript
var temperature = [];
var cityName = 'warsaw';
var weatherSiteUrl = "http://cors-anywhere.herokuapp.com/https://www.metaweather.com/";
var weatherAPIUrl = weatherSiteUrl + "api/";
var cityLocation = weatherAPIUrl + "location/search/?query=";
var iconUrl = "https://www.metaweather.com/";
function drawWeather() {
$.getJSON(cityLocation + cityName, function(data) {
$.getJSON(weatherAPIUrl + 'location/' + data[0].woeid, function(data) {
$('.location').html(cityName + '<i class="fa fa-map-marker"></i>'); // Name of location
$('.weather-state').html(data.consolidated_weather[0].weather_state_name); //Weather state
temperature[0] = Math.floor(data.consolidated_weather[0].the_temp);
$('.temperature').html(temperature[0] + '<sup>°</sup><span class="unit">c</span>'); // Temperature
var weatherImg = iconUrl + 'static/img/weather/' + data.consolidated_weather[0].weather_state_abbr + '.svg';
$('.weather-icon').html('<img src=' + weatherImg + '>');
});
});
};
drawWeather();
Instead of hardcoding 'warsaw' pass the location to the function
var temperature = [];
var weatherSiteUrl = "http://cors-anywhere.herokuapp.com/https://www.metaweather.com/";
var weatherAPIUrl = weatherSiteUrl + "api/";
var cityLocation = weatherAPIUrl + "location/search/?query=";
var iconUrl = "https://www.metaweather.com/";
function drawWeather(cityName) {
$.getJSON(cityLocation + cityName, function(data) {
$.getJSON(weatherAPIUrl + 'location/' + data[0].woeid, function(data) {
$('.location').html(cityName + '<i class="fa fa-map-marker"></i>'); // Name of location
$('.weather-state').html(data.consolidated_weather[0].weather_state_name); //Weather state
temperature[0] = Math.floor(data.consolidated_weather[0].the_temp);
$('.temperature').html(temperature[0] + '<sup>°</sup><span class="unit">c</span>'); // Temperature
var weatherImg = iconUrl + 'static/img/weather/' + data.consolidated_weather[0].weather_state_abbr + '.svg';
$('.weather-icon').html('<img src=' + weatherImg + '>');
});
});
};
Then instead of drawWeather(); run the function using drawWeather('warsaw');, drawWeather('berlin');,...
I want to javascript loop for wrapping two line of products layouts after i got a respond from ajax.
Purposed: I want to get result like below
<div class="owl-item">
<div class="row item">
<div class="product">
<div class="image">
<img src="asset/img/main/9.jpg" alt="img">
<div class="promotion"><span class="discount">4</span></div>
<div class="description">
<div class="price"><span>1.0000</span></div>
<h4></h4><p>short detial</p>
</div>
</div>
</div>
</div>
<div class="row item">
<div class="product">
<div class="image">
<img src="9.jpg"alt="img">
<div class="promotion"><span class="discount">4</span></div>
<div class="description">
<div class="price"><span>2.0000</span></div>
<h4></h4>
<p>short detial</p></div>
</div>
</div>
</div>
</div>
As the above html planned I want to loop <div class="owl-item"> one times then I will loop <div class="row item"> two times So my html layout will wrap my products as the below images.
$.ajax({
type: "GET",
url: "<?php echo base_url('main/dataaccess'); ?>",
dataType: "json",
cache: false,
success: function (data, st) {
if (st == 'success') {
$.each(data, function (i, obj) {
var out = '<div class="row item">';
out += '<div class="product">';
out += '<div class="image">';
out += '<img src="asset/img/main/9.jpg" alt="img" class="img-responsive">';
out += '<div class="promotion"><span class="discount">' + obj.prodId + '</span> </div>';
out += '<div class="description"><div class="price"><span>' + obj.prodPrice + '</span></div><h4>' + obj.prodName + '</h4>';
out += '<p>short detial</p>';
out += '</div>';
out += '</div>';
$(out).appendTo("#ps");
});
$("#ps").owlCarousel({
navigation: false,
pagination: false,
items: 8,
itemsTablet: [408, 2]
});
}
}
});
This is the layout that i want to get
But as my code I will got layout as below that I don't want it
Are one of those classes that are applying to your div set as display:inline-block ? I suggest inspecting the rendered page to confirm that the divs are display: block.