Show images src from ajax - javascript

Requesting path for img src via below code:
$.ajax({
url: 'api/catalogs.php?action=fetchimg&CatalogId=' + d.CategoryId,
type: 'GET',
dataType: "json",
success: function(response) {
var path = response.path;
console.log(path);
$.each(response, function(key, value) {
$("#images").attr('src', value.path);
})
},
});
But code displaying only one photo, API returning many photos and need to display all.
For displaying I am using below code.
return '<div class="container">'+
'<div class="row justify-content-center text-center my-3"></div>'+
'<div class="row justify-content-center text-center">'+
'<div class="col-md-4 mb-3">'+
'<img id="images" src="" class="img-fluid img-thumbnail"></a>'+
'</div>'+
'</div>'+
'</div>';

Your code is only editing one image src. You should do something like this in your success in $.ajax
$.each(response, function(key, value){
$("body").append($("<img>", { src: value.path } ));
})
This will add an image to the body for each of the paths in your response. Then you can start modifying this to your requirements

Because you are using the same ID for all elements (#images). You need to make it dynamic like add counter with it like ('#images' + counter);
and the same thing needs to change in HTML.

Finally, see below
$.ajax({
url: 'api/catalogs.php?action=fetchimg&CatalogId='+d.CategoryId,
type: 'GET',
dataType: "json",
success: function(response) {
var images = "";
$.each(response, function(key, value){
images+='<div class="col-md-4 mb-3">'+
'<img src="'+value.path+'" class="catalog-image img-responsive thumbnail"></a>'+
'</div>';
})
$('#photos').html(images);
},
in HTML above code inserting into below div:
<div class="container">
<div id="photos" class="row justify-content-right text-right my-3"></div>
<div class="row justify-content-right text-right">
</div>
</div>

Related

Load list objects in ajax response and create dynmic list divs with this data

I have this part of HTML:
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text">{content}</p>
Read...
</div>
</div>
</div>
</div>
</div>
and I have ajax request which calls after page loading:
<script>
$(window).on('load', function () {
loadArticles();
});
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles", success: function (result) {
}
});
}
</script>
I need to create list of cards(<div class="card">) with data from response. For example, I get 5 articles in response. I need to create 5 card divs and fill its data from the response. How can I do it?
Loop over the objects you get back from the ajax call and use the jQuery .append() function to add them to the dom.
First, you need to add an identifying class (or id) to the parent div in your HTML and remove the card HTML:
<div class="container">
<div class="row">
<div class="col-sm-4 cards-wrapper"></div>
</div>
</div>
Then in your loadArticles function loop over your ajax response and append to that jQuery selected we just defined - '.cards-wrapper':
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles",
}).done(function(data) {
const cards = data.body.cards; // Or however you need to traverse the response object
cards.forEach(function(card) {
$('.cards-wrapper').append('<div class="card"><div class="card-body"><h4 class="card-title">' + card.title + '</h4><p class="card-text">' + card.content + '</p>Read...</div></div>');
})
});
}
Ideally you should extract out that append code into its own function for readability, etc.
You can do it by simply using html template
HTML
First you need to add card-container id to the HTMl tag in which we will inject HTMl using ajax
<div class="container">
<div class="row">
<div class="col-sm-4" id="card-container">
</div>
</div>
</div>
Javascript
<script>
$(window).on('load', function () {
loadArticles();
});
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles", success: function (result) {
//Get template html using ajax and append it with **card-container**
var cardTemplate = $("#cardTemplate").html();
result.forEach(function (card) {
$('#card-container').append(cardTemplate.replace("{title}",
card.title).replace("{content}", card.content));
})
}
});
}
</script>
HTML Template
Assign id cardTemplate to html template
<template id="cardTemplate">
<div class="card">
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text">{content}</p>
Read...
</div>
</div>
</template>
I have also implemented on my end so it will surely gonna work !!!

Loop inside template literals JS

I have objects like these.
{image: "img", images: "["1561971738beach-2179624_960_720.jpg","1561971738…"1561971738photo-1507525428034-b723cf961d3e.jpg"]", name: "aaa", surname: "bbb", text: "test", …}
image: "img"
images: "["1561971738beach-2179624_960_720.jpg","1561971738pexels-photo-457882.jpeg","1561971738photo-1507525428034-b723cf961d3e.jpg"]"
name: "aaa"
surname: "bbb"
text: "test"
user_id: 2
The images field contains JSON of pictures each post has. How can I put each post's images inside of it while printing the post out?
My code:
$.ajax({
url: '/loadPosts',
type: 'GET',
dataType: 'json',
data: {_token: "{{ csrf_token() }}"},
success: function(r){
r.forEach((post)=>{
var images = JSON.parse(post.images);
$('.posts-div').append(`
<div class="card mb-3">
<h5 class="card-header">
<img src="images/${post.image}" style="width: 35px; height: 35px;">
${post.name} ${post.surname}
</h5>
<div class="card-body">
<p class="card-text">${post.text}</p>
NEED TO PUT IMAGES HERE.
<div class="heart-div">
<img class="heart" src="http://www.clipartroo.com/images/96/black-heart-clipart-96717.png">
</div>
</div>
</div>
`);
})
}
})
You iterate trought the post images array, like this:
Create a variable string.
Store the content until the place where the images are.
We iterate the images, and store it in string.
We add the bottom html to the string.
Finally you append it with append().
$.ajax({
url: '/loadPosts',
type: 'GET',
dataType: 'json',
data: {_token: "{{ csrf_token() }}"},
success: function(r){
r.forEach((post)=>{
var string = `<div class="card mb-3">
<h5 class="card-header">
<img src="images/${post.image}" style="width: 35px; height: 35px;">
${post.name} ${post.surname}
</h5>
<div class="card-body">
<p class="card-text">${post.text}</p>`;
for(image in post.images){
var string = string + `<img src="images/${image}" style="width: 35px; height: 35px;">`;
}
var string = string + `<div class="heart-div">
<img class="heart" src="http://www.clipartroo.com/images/96/black-heart-clipart-96717.png">
</div>
</div>
</div>`;
$('.posts-div').append(string);
})
} })
Here is the entire ajax call, just copy paste, I did not "compile" it so maybe there are some syntax error, but the logic is flawless, so tell me how it works.

fade out and fade in card element

I'm trying to fade out and fade in a card element. My html looks like this:
<form class=" mt-4 mw-800 center-block animated fadeInUp">
<div class="row">
<div class="col-lg-12 content">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">{{ $random_idea->title }}</h3>
</div>
<div class="card-body">
{{ $random_idea->description }}
</div>
</div>
</div>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button id="idea" type="button" class="btn btn-raised btn-primary btn-block">
Geef mij een ander idee</button>
</form>
My jQuery code looks like this:
$( "#idea" ).click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$.ajax({
type: "POST",
url: "/idea",
success: function(response) {
$(".card").fadeOut();
$('<div class="card card-primary">' +
'<div class="card-header">' +
'<h3 class="card-title">' + response.title + '</h3>' +
'</div>' +
'<div class="card-body">' + response.description +
'</div>' +
'</div>').appendTo('.content').fadeIn();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
The card div is fading out and fading in. But there is a delay, it's not shown good.
My lay-out looks like this:
When you click on the button the card fades out and another card fades in. But it's not smooth. Do you have any ideas to help me?
jQuery fadeIn() and fadeOut() are asynchronous. So, the new and old elements are fading in/out together. But, those methods gets a callback will call after the animation. So, you can rewrite your success function as follows:
$(".card").fadeOut(function() {
$(this).remove();
$('<div class="card card-primary">' +
'<div class="card-header">' +
'<h3 class="card-title">' + response.title + '</h3>' +
'</div>' +
'<div class="card-body">' + response.description + '</div>' +
'</div>').appendTo('.content').fadeIn();
});
Try using this
var html = '<div class="card card-primary">' +
'<div class="card-header">' +
'<h3 class="card-title">' + response.title + '</h3>' +
'</div>' +
'<div class="card-body">' + response.description +
'</div>' +
'</div>';
$(html).hide().appendTo(".content").fadeIn(300);
The reason its not going smooth is because you didnt give a speed within your fadeout/fadein function.
If you read the docs on https://www.w3schools.com/jquery/eff_fadeout.asp you notice the syntax accepts a speed $(selector).fadeOut(speed,easing,callback)
Wenn you fill in the speed of your fadein() and your fadeout() it should go smooth.

Ajax json display data correctly

I'm trying to display the data from json in my HTML. It doesn't seem to get the data properly.
I'm running it on my localhost so I can see the json properly. here on my demo, the json is hosted on my personal FTP.
How can I display the data in my HTML?
$(function() {
ajaxJS();
function ajaxJS(e) {
if (e) {
e.preventDefault();
}
$.ajax({
url: "http://www.domenghini.com/sample-data.json",
method: "GET",
success: function(data) {
console.log(data);
var html_to_append = '';
$.each(data.items, function(i, items) {
html_to_append +=
'<div class="col-3 mb-3"><div class="name text-left pb-1 text-uppercase"><p>' +
name.first +
'<div class="col-3 mb-3"><div class="last text-right pb-1 text-uppercase"><p>' +
name.last +
'</p></div><img class="image img-fluid" src="' +
picture +
'" /><p class="company">' +
company +
'</p></div>';
});
$("#items-container").html(html_to_append);
},
error: function() {
console.log(data);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div id="items-container" class="row"></div>
</div>
I think the issue is you are trying to access name.first name.last in $.each without specifying items.name.first
$(function() {
ajaxJS();
function ajaxJS(e) {
if (e) {
e.preventDefault();
}
$.ajax({
url: "http://www.domenghini.com/sample-data.json",
method: "GET",
success: function(data) {
console.log(data);
var html_to_append = '';
$.each(data, function(i, item) {
html_to_append +=
'<div class="col-3 mb-3"><div class="name text-left pb-1 text-uppercase"><p>' +
item.name.first +
'<div class="col-3 mb-3"><div class="last text-right pb-1 text-uppercase"><p>' +
item.name.last +
'</p></div><img class="image img-fluid" src="' +
item.picture +
'" /><p class="company">' +
item.company +
'</p></div>';
});
$("#items-container").html(html_to_append);
},
error: function() {
console.log(data);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div id="items-container" class="row"></div>
</div>

i want to associate links to respective article on dynamically created p element

here is my codepen link
my html code
<div id="main">
<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
Surprise me!
</div>
<div id="search">
</search>
jquery code for making wikipedia api search call and then displaying title and overview.i want to associate links to respective article on dynamically created p element
$(document).ready(function() {
$("button").click(function() {
var article = $("input").val();
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {
for (var i = 0; i < data.query.search.length; i++) { //displaying titles and snippets accroding to search query. i want to associate link to each dynamically created p element.
var title = data.query.search[i].title;
var snippet = data.query.search[i].snippet;
$("#search").append("<p>" + title + "<br>" + snippet + "</p>");
}
$("#main").attr({
'style': 'display: none'
});
},
error: function() {
$("h1").html("oops");
}
});
});
});
Change your $("#search").append() as follows:
$("#search")
.append("<p><a href='https://en.wikipedia.org/wiki/" + title + "'>" + title + "</a>" +
"<br>" + snippet + "</p>"
);
Codepen

Categories

Resources