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();
Related
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!");
}
});
var serviceURL = "http://mywebsite.com/mobile/";
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="reportlist.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
My problem with my script is that any time i try to reach server and it is down i want my application to be alert people that the server is down for now
var serviceURL = "http://mywebsite.com/mobile/";
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
// Use the ajaxError method to handle your error
$(document).ajaxError(function(event, request, settings) {
//Then you can use the .hide() to hide div alert users for error
$('#errorserver').hide();
alert("Error accessing the server");
});
function getEmployeeList() {
//Then you can use the .show() to show loading
$('#errorserver').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
//Then you can use the .hide()
$('#errorserver').hide();
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="reportlist.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
//Add this div to your html page
<div id="errorserver"/><img src="image/loading.png" alt="Loading please wait.."></div>
You have to handle errors using .fail method:
$.getJSON(serviceURL + 'getemployees.php', function(data) {
// ... your implementation
}).fail(function (err) {
// ... this callback will be invoked
// ... in case any error of the server
});
How can I get the value from an input field when I click the button using jquery?
Below is my Jquery code :
asset_status_list = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>operations/asset_status",
dataType: "JSON",
success: function (response) {
for (i = 0; i < response.length; i++) {
asset_status_list = '<tr><td >' + response[i].job_card_no + '</td><td >' + response[i].number + '</td><td>' + response[i].type + '</td><td ><input type="text" name="view_more_id" class="view_more_id' + response[i].asset_id + ' btn btn-default" id="view_more_id" value="' + response[i].asset_id + '"/><button id="view_more_link" class="view_more_link' + response[i].asset_id + '"><i class="glyphicon glyphicon-zoom-in "></i>View More</button></td></tr>';
$('#asset_status_tr').append(asset_status_list);
$("#asset_status_tr").on("click", ".view_more_link" + response[i].asset_id, function () {
console.log(response);
var asset_id = this.value;
alert(asset_id);
});
}
$('#asset_table_status').DataTable({});
},
error: function (response) {
}
});
I want to get the value of the input field name view_more_id .
Is this the answer you are looking for ? var asset_id = $( "#view_more_id" ).val();
I have selectize js code. It runs well and shows right option after i type key on select box.
Here is the code :
$('#select-links').selectize({
maxItems: diffItems,
valueField: 'nick_name',
labelField: 'full_name',
searchField: ['nick_name', 'full_name'],
options: [],
create: false,
render: {
item: function(item, escape) {
return '<div id="' + escape(item.id) + '">' +
'<span class="nick_name">' + escape(item.full_name) + '</span>' +
'<span class="full_name"> <' + escape(item.nick_name) + '></span>' +
'</div>';
},
option: function(item, escape) {
return '<div class="box-user clearfix">' +
'<div class="thumb col-xs-1 mr10">' +
'<img class="lazyload" src="'+escape(item.avatar)+'" data-src="' + escape(item.avatar)+'">' +
'</div>' +
'<div class="col-xs-8">' +
'<span class="label" style="color: #000;">' + escape(item.full_name) + '</span>' +
'<span class="caption">/' + escape(item.nick_name) + '</span>' +
'</div>' +
'</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/ajax/origin/search',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
}
});
But, i got the problem.
After document ready, i want selectize add item automatically after document / page has already loaded without i have to type the key on select box. How is the code?
#if(isset($_POST['nick']))
$(".chat__list--active").show();
$(".edit").hide();
$('.chat__list').hide();
$('#cancel-participants').show();
if(diffItems != 49) {
$('#save-participants').show();
}
alert("{{$_POST['nick']}}");
// This is the code's place to add item automatically and the key is $_POST['nick']
#endif
Thank you.
Sorry for bad english
You can add options to existing selectize by following approach:
$(document).ready(function(){
var selectize_element = $("#select-links")[0].selectize;
selectize_element.addOption({
text:'First Item',
value: 'First Item'
});
selectize_element.refreshOptions() ;
selectize_element.addItem('First Item');
});
(function () {$('.KisiSilici').click( function () {
does not working .click, .on, .live, is my try but not work. Thanks for your help.
maybe it was because I fill the table with ajax
$(document).ready(function Kisilertabs() {
$(function () {
$("#tabs").tabs();
});
var id = #Model.ID.ToString()
$.ajax({
url: '#Url.Action("Kisiler", "Cihazlar")',
type: "get",
contentType: "application/json; charset=utf-8",
data: { data: id },
dataType: "json",
success: function (data) {
var row = "<tr><th width='70'>S. No</th><th width='220'> Adı </th><th width='220'>Soyadı</th><th>Sicil No</th><hr/></tr>";
$.each(data, function (index, item) {
row += "<tr id='" + item.ID + "'><td>" + item.ID + "</td ><td>" + item.Adi + "</td><td>" + item.Soyadi + "</td><td>" + item.Sicil + "</td><td><a href='/Kullanicilar/Details/" + item.ID + "'><img width='15' src='../../Content/images/Detay.png'></a></td><td><input id='Kisisec' value='" + item.ID + "' class='KisiSilici' type='image' width='20' src='../../content/images/sil.png' /></td></tr><hr />";
});
$("#Kisiler").html(row);
},
error: function (result) {
alert("Error");
}
})
});
$(function problem () {
$('.KisiSilici').click( function () {
var ip = "";
$.ajax({
url: '#Url.Action("KisilerSil", "tabs")',
type: "POST",
data: { data: ip },
success: function (data) {
var row = "<p>" + data + "</p>";
$("#CihazKontrol").prepend(row);
},
error: function (result) {
alert("Error");
},
})
});
});
There are few problems with this code:
$(document).ready(...) is exactly the same as $(...), so using $(...) inside $(document).ready(...) doesn't make any sense. You could loose $(...) wrapping.
The problem name given to anonymous function gives us an error. The function used as arguments are meant to be anonymous or just references (names) to another functions so you can do it like this:
$(function() {
//do smth
});
or this:
function do(){
//do smth
}
$(do);
So your code, as I see it, should look more like this: (it's hard to tell your point here)
$(document).ready(function Kisilertabs() {
$("#tabs").tabs();
var id = #Model.ID.ToString()
$.ajax({
url: '#Url.Action("Kisiler", "Cihazlar")',
type: "get",
contentType: "application/json; charset=utf-8",
data: { data: id },
dataType: "json",
success: function (data) {
var row = "<tr><th width='70'>S. No</th><th width='220'> Adı </th><th width='220'>Soyadı</th><th>Sicil No</th><hr/></tr>";
$.each(data, function (index, item) {
row += "<tr id='" + item.ID + "'><td>" + item.ID + "</td ><td>" + item.Adi + "</td><td>" + item.Soyadi + "</td><td>" + item.Sicil + "</td><td><a href='/Kullanicilar/Details/" + item.ID + "'><img width='15' src='../../Content/images/Detay.png'></a></td><td><input id='Kisisec' value='" + item.ID + "' class='KisiSilici' type='image' width='20' src='../../content/images/sil.png' /></td></tr><hr />";
});
$("#Kisiler").html(row);
},
error: function (result) {
alert("Error");
}
})
});
$('.KisiSilici').click( function () {
var ip = "";
$.ajax({
url: '#Url.Action("KisilerSil", "tabs")',
type: "POST",
data: { data: ip },
success: function (data) {
var row = "<p>" + data + "</p>";
$("#CihazKontrol").prepend(row);
},
error: function (result) {
alert("Error");
},
});
});