Append external json data to div category wise - javascript

i dont know how to append external json data to div. i know append with table .but, i am confused with div.please help me to solve this doubt.
because,it need to append data with selected category div.
div1 category [books]
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-2 card">
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Card title</h4>
<!--Text-->
<img class="img-fluid z-depth-3 rounded-circle" src="https:/goo.gl/4cPCdn"
alt="Card image cap">
<h4 class="card-title">Category</h4>
<!--Card content-->
Button
</div>
</div>
div 2 category [games]
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-2 card">
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Card title</h4>
<!--Text-->
<img class="img-fluid z-depth-3 rounded-circle" src="https:/goo.gl/4cPCdn"
alt="Card image cap">
<h4 class="card-title">Category</h4>
<!--Card content-->
Button
</div>
</div>
Json
{
"category": {
"books": [
{"title":"Sentra", "url":"https:/goo.gl/4cPCdn","button":"https:google.in"},
{"title":"Maxima", "url":"https:/goo.gl/4cPCdn"},"button":"https:google.in"}
],
"games": [
{"title":"Taurus", "url":https:/goo.gl/4cPCdn},"button":"https:/google.in"}
{"title":"Escort", "url":https:/goo.gl/4cPCdn},"button":"https:/google.in"}
]
}
}
Javascript & jquery
<script>
$.ajax({
url: 'json-data.json',
type: "get",
dataType: "json",
success: function (data) {
drawTable(data);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
**This part i dont know please teach me**
}
</script>
Fiddle
Fiddle codes click to edit

This isn't perfect but it should give you some help in understanding how to append to a div via jQuery. Your data was messed up, so I fixed it and made it a valid object. You may want to use things like JSLint to check your data before testing your pages - https://jsonlint.com/
var data = {
"category": {
"books": [
{"title":"Sentra", "url":"https:/goo.gl/4cPCdn", "button":"https:google.in"},
{"title":"Maxima", "url":"https:/goo.gl/4cPCdn", "button":"https:google.in"}
],
"games": [
{"title":"Taurus", "url":"https:/goo.gl/4cPCdn","button":"https:/google.in"},
{"title":"Escort", "url":"https:/goo.gl/4cPCdn","button":"https:/google.in"}
]
}
}
/* not needed for test, we've already included our data above
$.ajax({
url: 'json-data.json',
type: "get",
dataType: "json",
success: function (data) {
drawTable(data);
}
});
*/
data = data.category;
drawTable(data)
function drawTable(theData) {
for (category in theData) {
console.log('category is '+category)
var categoryEntries = theData[category]
for (var i = 0; i < categoryEntries.length; i++) {
var rowData = categoryEntries[i];
drawRow(category,rowData)
}
}
}
function drawRow(category,rowData) {
// console.log(JSON.stringify(rowData))
var title = rowData.title;
var url = rowData.url;
var button = rowData.button
var newDiv = '<div class="card">'+
'<div class="card-body">'+
'<h4 class="card-title">'+title+'</h4>'+
'<img class="img-fluid z-depth-3 rounded-circle" src="'+url+'" alt="Card image cap">'+
'<h4 class="card-title">'+category+'</h4>'+
'Button'+
'</div>'+
'</div>'
$('#'+category).append(newDiv);
}
#books,#games {
display:block;
width: 100%;
clear:both;
}
.card {
float:left;
width: 30vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="books">
</div>
<div id="games">
</div>

Related

Independent HTTP status for each array element

I am using the following code to print some information in HTML.
I have problems.
First, I use:
fetch(resultado.url).then(function(response) {console.log(response.status);
To obtain the http status of the URL that is inside the array "channelList", but I don't know how to get that state independently, I mean, for all elements of the array.
And after that, if I change 'getElementbyID' to 'getElementbyClassName' to show 'status' in HTML, this doesn't work
const channelList = [
{
name: "La 1",
title: "RTVE La 1",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "./la1.html",
},
{
name: "La 2",
title: "RTVE La 2",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "./la2.html",
},
];
const resultado = channelList.find( canal => canal.name === 'La 1' );
// HTTP STATUS
fetch(resultado.url).then(function(response) {
console.log(response.status);
if(response.status !== 200){
let stt = document.getElementById('hlstatus');
stt.innerText = "Offline";
} else {
document.getElementById('hlstatus').innerText = "Online";
}
});
// PRINT ON HTML
const container = document.getElementById("locales");
var img = "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e";
channelList.forEach(result => {
// Construct card content
const content = `
<div class="col-6 col-sm-4 col-lg-3 col-xl-2">
<div class="dropdown card darkolorbg text-white card-canal card-link text-white">
<a class="card-link text-white" href="${result.link}" ${result.dDown}>
<div class="card-body">
<div class="d-flex justify-content-center">
<img class="canal-img ${result.imgClass}" src="${img}" alt="">
</div>
<div class="d-flex justify-content-center"><h5>${result.name} <span class="hidden">${result.title}</span> <br><span class="subtf1"><i class="flag ${result.flag}"></i></span> <span id="hlstatus"></span> </div>
</div>
</a>
</div>
</div>
`;
// Append newyly created card element to the container
container.innerHTML += content;
});
<div id="locales"></div>
If I understood you correctly, this code should work as you expect.
But pay attention, please, to error processing.
It could be done by passing callback function to .catch method of the promise.
var img = "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e";
const container = document.getElementById("locales");
// PRINT ON HTML
function makeStatusCard(result) {
const content = `
<div class="col-6 col-sm-4 col-lg-3 col-xl-2">
${result.status}
<div class="dropdown card darkolorbg text-white card-canal card-link text-white">
<a class="card-link text-white" href="${result.link}" ${result.dDown}>
<div class="card-body">
<div class="d-flex justify-content-center">
<img class="canal-img ${result.imgClass}" src="${img}" alt="">
</div>
<div class="d-flex justify-content-center"><h5>${result.name} <span class="hidden">${result.title}</span> <br><span class="subtf1"><i class="flag ${result.flag}"></i></span> <span id="hlstatus"></span> </div>
</div>
</a>
</div>
</div>
`;
// Append newyly created card element to the container
container.innerHTML += content;
}
const channelList = [
{
name: "La 1",
title: "RTVE La 1",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "https://avax.dev/data/validators.json",
},
{
name: "La 2",
title: "RTVE La 2",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "https://avax.dev/data/validators.json",
},
];
// HTTP STATUS
for (let channel of channelList) {
fetch(channel.url).then(function(response) {
channel.status = response.status === 200 ? 'Online' : 'Offline';
makeStatusCard(channel);
});
}
<div id="locales"></div>

InnerHTML not rendering as expected

I am currently making an Ajax call which returns an array of different projects in a portfolio.
Once the call is successful, I want to loop through the array and create a bootstrap carousel displaying each project name and details as a carousel item.
The issue that I'm having is that when I try to add HTML-code to the #project-carousel and #project-carousel-indicators, nothing shows up.
<div class="row" id="project-section">
<div class="col-lg-12">
<div class="carousel slide" data-ride="carousel" id="project-carousel">
<ol class="carousel-indicators" id="project-carousel-indicators">
<!-- loop -->
</ol>
<div class="carousel-inner" id="inner-project-carousel">
<!-- loop -->
</div>
</div>
</div>
</div>
document.addEventListener('DOMContentLoaded', getProjects(), false);
function getProjects() {
$.ajax({
url: '/Portfolio/getProjects',
type: 'POST',
async: false,
success: function(result) {
var innerCarousel = document.getElementById('inner-project-carousel');
var carouselIndicators = document.getElementById('project-carousel-indicators');
for (var i = 0; i < result.length; i++) {
if (i === 0) {
//This is being hit but it doesn't render the innerHTML
carouselIndicators.innerHTML = `<li data-target="#project-carousel" data-slide-to="${i}" class="active"></li>`;
innerCarousel.innerHTML =
`<div class="item active">
<div class="row item-wrapper">
<div class="col-lg-5">
<h3>${result[i].Client}</h3>
<p>${ result[i].Description}</p>
</div>
</div>
</div>`;
} else {
//this is also being hit but it doesn't render the innerHTML
carouselIndicators.innerHTML = `<li data-target="#project-carousel" data-slide-to="${i}"></li>`;
innerCarousel.innerHTML =
`<div class="item">
<div class="row item-wrapper">
<div class="col-lg-5">
<h3>${result[i].Client}</h3>
<p>${ result[i].Description}</p>
</div>
</div>
</div>`;
}
}
},
error: function(event, jqxhr, settings, excpetion) {
showError(event, jqxhr, settings, excpetion);
}
});
}
Call carousel manually after you append the html content.
$('.inner-project-carousel').carousel();

How to response ajax search output to view ~laravel

I am trying to send json response on my ajax into my view on my laraveL.
But i can't get any good codes for it, exam
public function viewMasakanAjax(Request $request)
{
if($request->ajax())
{
$alberMasakan = Masakan::where('alber_nama_masakan','LIKE','%'.$request->search."%")->get();
return response()->json($alberMasakan)->view('kasir/ajax-menu');
}
}
When i am try that code, it doesn't work.
also this is my view
#foreach($alberMasakan as $alberData)
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-12 col-12">
<div class="card card-figure">
<figure class="figure">
<div class="figure-img">
<figure class="figure">
<img class="img-fluid" src="{{ asset('kasir/images/seafood.jpg') }}" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"> Simple figure </h6>
<p class="text-muted mb-0"> Give some text description </p>
</figcaption>
</figure>
</figure>
</div>
</div>
#endforeach
here my ajax code
<script>
$('#cariData').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('admin.ajax')}}',
data:{'search':$value},
success:function(data){
$('.ajax').html(data);
if ($value == '') {
$('.isi').remove();
}
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
my route on web.php
Route::get('/cari', 'KasirRestoran\DetailOrderController#viewMasakanAjax')->name('admin.ajax');
You can return either $response->json() or view(), but not both together.
Your javascript is expecting to see HTML content, but you're feeding it JSON data. To pass data to a view, use something like this:
public function viewMasakanAjax(Request $request)
{
if ($request->ajax()) {
$alberMasakan = Masakan::where('alber_nama_masakan','LIKE','%'.$request->search."%")->get();
// Pass $alberMasakan as data along to the view
// Same as view('kasir/ajax-menu')->with($alberMasakan)
return view('kasir/ajax-menu', $alberMasakan);
}
}
You should try
public function viewMasakanAjax(Request $request)
{
if($request->ajax())
{
$alberMasakan = Masakan::where('alber_nama_masakan','LIKE','%'.$request->search."%")->get();
return response()->json($alberMasakan);
}
}

Show posts with ajax - Use of undefined constant postObj - assumed 'postObj'

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.

How to make two times for a loop in javascript?

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.

Categories