Ajax request cached for 1 minute. Meaning that no additional requests should be made when you reload the page during this time.
What would be a correct way to:
After first page load, sets Ajax timeout for 1 minute.
If user reloads page before that 1 minute has gone past, values of ajax should stay the same.
Ajax on document ready -
$.ajax({
type: "GET",
dataType: 'json',
url:"",
cache: true, //It must "true" if you want to cache else "false"
//async: false,
success: function (data) {
var resData = JSON.stringify(data.items);
var items = JSON.parse(resData);
console.log(data.totalItems);
$('button.cart').append('<span class="cart-info">' +data.totalItems+ ' Items in your cart ' + '<span class="totalPrice-cart">€' + data.totalPrice + '</span></span>');
$.each(items,function(i,v){
console.log(v.name);
console.log(v);
$('ul.dropdown-cart').prepend(
'<li>'+
'<div class="item">'+
'<div class="item-left">' +
'<img src="'+ v.imgSrc +'" style="width:100%; height:auto;" alt="">' +
'</div>' +
'<div class="item-middle">' +
'<div class="cart-title text-uppercase">'+ v.name + '</div>' +
'<div class="cart-price">'+ v.qty + ' x € ' + v.price + '</div>' +
'</div>' +
'<div class="item-right">' +
'<button class="cart-delete "><img src="../public/img/web/Delete.png" alt=""></button>' +
'</div>' +
'</div>'+
'</li>'
);
});
},
error: function (xhr, textStatus, error) {
alert("Error Happened!");
}
});
Related
I'm currently working on a code that displays users activity log. Ajax will call the route and gets the response (json) results. I need to be able to display the log records on admin dashboard without refreshing the page.
Ajax
$(document).ready(function() {
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
},error:function(){
console.log(data);
}
});
});
If I understood, you can do this:
$(document).ready(function() {
var requesting = false;
var request = function() {
requesting = true;
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
requesting = false;
});
});
},error:function(){
console.log(data);
}
});
};
if(!requesting){
setTimeout(request, 1000);
}
});
Every seconds it does a request to your users.activity route, so there is an update every second.
You need to send last record id in server. so you can get only new data.
my updated answer based on #stackedo answer .
$(document).ready(function () {
var lastId = 0; //Set id to 0 so you will get all records on page load.
var request = function () {
$.ajax({
type: 'get',
url: "{{ route('users.activity') }}",
data: { id: lastId }, //Add request data
dataType: 'json',
success: function (data) {
$.each(data, function () {
$.each(this, function (index, value) {
console.log(value);
lastId = value.id; //Change lastId when we get responce from ajax
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
}, error: function () {
console.log(data);
}
});
};
setInterval(request, 1000);
});
In controller add were condition to query :
UserActivity::where('id','>',$request->id)->get();
I'm using the google news API and I want to add the value of the URL to be on the article title and convert the image from the JSON data to be viewable. Below is my code so far.
/*$.getJSON(url, function(data){
console.log(data);
});*/
$.ajax({
url:
"https://newsapi.org/v2/everything?apiKey=xxx&q=nrcs",
dataType: "json",
type: "get",
cache: false,
success: function (data) {
$(data.articles).each(function (index, value) {
//console.log(value);
$('#news').append('<div>' + '<h3 id="title" style="color:#B8860B;">' + value.title + '' + value.url + '</h3>' + '<p>' + '<span style="color:#C4BFBF; font-style: italic;">' + value.author + '</span>' + '<br>' + value.publishedAt + '<br>' + value.description + '</p>' + '</div>');
$('#link').append(value.url);
});
}
});
Judging just by this and not seeing the whole picture (returned Json, css styles and layout of the page; basically any conflicting factors) I’d try:
$.ajax({
url:
"https://newsapi.org/v2/everything?apiKey=xxx&q=nrcs",
dataType: "json",
type: "get",
cache: false,
success: function (data) {
$(data.articles).each(function (index, value) {
//console.log(value);
$('#news').append('<div>' + '<h3 id="title" style="color:#B8860B;">' + value.title + '' + value.url + '</h3>' + '<p>' + '<span style="color:#C4BFBF; font-style: italic;">' + value.author + '</span>' + '<br>' + value.publishedAt + '<br>' + value.description + '</p>' + '<br>' + value.url + '</div>');
});
}
});
Instead of appending to the appended div, add it direct within; check the console for any errors and if there are none your issue may be related to the container / style of your page.
I have AJAX request to get Question1-Question10 from back-end
Here is code of request
<script>
$(document).ready(function() {
question_block();
});
function question_block() {
$.ajax({
url: '#Url.Action("QuestionBlocks", "Interwier")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function(result) {
var email = result;
for (var i = 0; i <= email.length - 1; i++) {
var question = '<div style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question1 + '</div>'+
'<div style="font-size:20px;">' + email[i].Question2 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question3 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question4 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question5 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question6 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question7 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question8 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question9 + '</div>' +
'<div style="font-size:20px;">' + email[i].Question10 + '</div>';
$("#questions").append(question);
}
},
error: function() {
alert("Smth wrong in controller");
}
});
}
I need to make visible first div for default and when I click button, for example next I need to hide first div and make visible second, etc.
How I can do this?
<script>
$(document).ready(function() {
question_block();
});
function question_block() {
$.ajax({
url: '#Url.Action("QuestionBlocks", "Interwier")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function(result) {
var email = result;
for (var i = 0; i <= email.length - 1; i++) {
var question = '<div style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question1 + '</div>'+
'<div style="font-size:20px;">' + email[i].Question2 + '</div>' +
'<div style="font-size:20px;" class="que show'">' + email[i].Question3 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question4 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question5 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question6 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question7 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question8 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question9 + '</div>' +
'<div style="font-size:20px;" class="que hide">' + email[i].Question10 + '</div>';
$("#questions").append(question);
}
},
error: function() {
alert("Smth wrong in controller");
}
});
}
// click on next
function next(){
$(".que").each(function(){
if( $( this ).hasClass('show') ){
$( this ).removeClass("show").addClass('hide');
$( this ).next().removeClass("hide").addClass('show');
}
});
}
// same you can do for back button
use two classes "activeQue" and "hiddenQue"
by default give first question activeQue class and give hiddenQue to rest.
then you can use code like on next button to show hide questions
var element = $(".activeQue");
$(element).removeClass("activeQue").addClass("hiddenQue");
$(element).next().addClass("activeQue");
something like this
you can do this with set the second div take style="display:none" by default
and when you click you will hide fist div and show second div jquery code :
$("#first").slideUp();
$("#second").slideDown();
I'm trying to iterate through JSON data and populate the content dynamically using jQuery.
First I do an Ajax request
Then I loop through the data and create the HTML tags dynamically
I create a div container with a class of "product-wrapper" for each JSON object (in this case 2 divs product-wrapper). As you can see on the example of my JSON data, each object has an array of objects "details".
From my second foreach loop - how can I populate the data of "details" within its appropriate "product-wrapper" div?
JavaScript
myApp.init = function(){
var rates = {
products: $('.products-container'),
init: function(){
rates.showRates();
},
showRates: function(){
$.each(utils.rates, function(index, value){
rates.products.append(
'<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div class="product-details"></div>' +
'</div>'
);
$.each(value.details, function(i,val){
$('.product-details').append('<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>');
});
});
}
};
var utils = {
rates: '',
url: $('.business-interest-rates').attr('data-rates-json'),
init: function(){
utils.ajaxRequest();
},
ajaxRequest: function(){
$.ajax({
url: utils.url,
dataType: 'json',
success:function(data){
utils.rates = data;
if($('#interest-rates').length > 0){
rates.init();
}
},
error: function(e){
console.log(e.message);
}
});
}
};
utils.init();
};
JSON
[
{
"name":"Australian dollar (AUD)",
"currency":"AUD",
"details":[
{
"balance": "1+",
"grossRate": "1.700",
"aer": "0.5"
},
{
"balance": "500,000+",
"grossRate": "2.100",
"aer": "2.00"
},
{
"balance": "1,500,000+",
"grossRate": "2.450",
"aer": "1.00"
}
]
},
{
"name":"EURO (EU)",
"currency":"EU",
"details":[
{
"balance": "1+",
"grossRate": "1.700",
"aer": "1.50"
},
{
"balance": "500,000+",
"grossRate": "2.100",
"aer": "2.20"
}
]
}
]
Either don't use a CSS class to append your stuff but unique ids, or first generate the whole HTML code (wrapper and details all together) in one step and then append it.
// use unique IDs for appending
function () {
$.each(utils.rates, function (index, value) {
rates.products.append(
'<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div id="product-details-' + value.name + '"></div>' +
'</div>'
);
$.each(value.details, function (i, val) {
$('#product-details-' + value.name).append('<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>');
});
});
}
// first generate all html code, then append
function () {
$.each(utils.rates, function (index, value) {
var html = '<div class="product-wrapper">' +
'<div class="product-heading">' + value.name + '</div>' +
'<div class="product-details">';
$.each(value.details, function (i, val) {
html += '<div class="detail-row">' +
'<div class="detail detail-balance">' + val.balance + '</div>' +
'<div class="detail detail-gross-rate">' + val.grossRate + '</div>' +
'<div class="detail detail-aer">' + val.aer + '</div>' +
'</div>';
});
html += '</div>' +
'</div>';
rates.products.append(
html
);
});
}
I have a gallery setup with the lightbox plugin lightGallery
The gallery works perfect with static HTML. The problem arises when I dynamically grab API data and try to have the lightbox working on those items.
I can't seem to get another lightbox to both work with this function and load an HTML block from the page correctly (load the one that's been dynamically generated). This app does the correct HTML grabs, if I can get the conflict resolved.
Any initial thoughts? Anyone else run into anything similar?
JS:
//----------------------------------------------------------------//
//---------------// Calling Lightgallery //---------------//
//----------------------------------------------------------------//
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
// ----------------------------------------------------------------//
// ---------------// Unsplash Photos //---------------//
// ----------------------------------------------------------------//
// Filter Difference based on button click
$('button').click(function () {
$('button').removeClass("active");
$(this).addClass("active");
var unsplashAPI = "#URL";
var order = $(this).text();
var sortOptions = {
order_by: order,
format: "json"
};
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile" data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' aka: ' + photo.user.username + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes' + '</p>' + '</div>' + '</a>';
});
$('#photoBox').html(photoData);
}
$.getJSON(unsplashAPI, sortOptions, displayPhotos);
}); // End button
HTML:
<div class="content" id="photoBox"></div>
-- Thanks
Call the plugin after the data is appended to the page
function displayPhotos(data) {
var photoData = '';
$.each(data, function (i, photo) {
photoData += '<a class="tile" data-src="' + photo.urls.regular + '">' + '<img alt class="photo" src="' + photo.urls.regular + '">' + '<div class="caption-box" id="' + photo.id + '">' + '<h1 class="photo-title">' + 'Photo By: ' + photo.user.name + '</h1>' + '<p class="photo-description"> Description: Awesome photo by ' + photo.user.name + ' aka: ' + photo.user.username + ' So far this photo has ' + '<span>' + photo.likes + '</span>' + ' Likes' + '</p>' + '</div>' + '</a>';
});
$('#photoBox').html(photoData);
$('#photoBox').lightGallery({
selector: '.tile',
download: false,
counter: false,
zoom: false,
thumbnail: false,
mode: 'lg-fade'
});
}