I have data which are returned from my controller and thouse results are properly displayed as json inside js which appends div inside my view to show these data.
Now I have problem that with every click div is appended to +1 row to show same data.
How to delete these div on click action before appending new div.
success: function (result) {
var data = null;
$.each(result, function (i, item) {
data = '<div>' + item.Id + ' ' + item.Title + '</div>';
$("#tab-" + item.PropertyType).append(data);
});
Before you add a new set of divs you can delete all divs which have a parent div
whose name is starting with "tab-"
success: function (result) {
var data = null;
$("[id^='tab-'] div").remove();
$.each(result, function (i, item) {
data = '<div>' + item.Id + ' ' + item.Title + '</div>';
$("#tab-" + item.PropertyType).append(data);
});
Try this :
success: function (result) {
var data = null;
$.each(result, function (i, item) {
$("#tab-" + item.PropertyType).children('div').remove(); //remove any divs inside the tab
data = '<div>' + item.Id + ' ' + item.Title + '</div>';
$("#tab-" + item.PropertyType).append(data);
});
OR: Replace the entire content of the tab on success:
success: function (result) {
$.each(result, function (i, item) {
$("#tab-" + item.PropertyType).html('<div>' + item.Id + ' ' + item.Title + '</div>');
});
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 have a django model and I view i am aggregating few columns and filtering result and returning as below
def show_grid_summery(request):
id = request.GET.get('id', None)
context = {
"summery": [],
}
result = Records.objects.filter(grid_id_id = id).aggregate(Sum('house_count'), Sum('point_count'))
if len(result) != 0:
context["summery"].append([result['house_count__sum'], result['point_count__sum']])
return JsonResponse(context)
And on the template i am getting results using ajax
$.ajax({
url: 'ajax/summery/',
data: {
'id': ID
},
dataType: 'json',
success: function (data) {
alert(data);
var trHTML = '';
document.getElementById('summaryLabel').innerHTML = '';
$.each(data.summery , function (item) {
trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});
$('#summaryLabel').append(trHTML);
}
Now I want to fill the results record (2 columns) as a table inside the #summaryLabel tag. (preferably with headers as well). But I am unable to sort it out after many different attempts.
html part is
<table id="summaryLabel">
<p>information.</p>
</table>
The jQuery $.each() function passes two parameters, the first is the array index, the second is the object. So it would seem that in your code, your item variable would contain the index, which is not what you want.
Try:
$.each(data['summery'] , function (i, item) {
trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>';
});
or just
$.each(data['summery'] , function () {
trHTML += '<tr><td>' + this[0] + '</td><td>' + this[1] + '</td></tr>';
});
jQuery $.each() is documented here: http://api.jquery.com/jquery.each/
I'm retrieving data from a database via AJAX GET call, ater succesfull response I print the data by appending an html template to my table, I am getting the results back all right (in JSON format) but when appending them to table they all appear as undefined:
Here is my controller method:
public function index()
{
$reviews = Review::all();
return response()->json([
'success' => 'Todas las opiniones recogidas',
'reviews' => $reviews,
]);
}
This is my JQuery code where I append the results, I'm fairly certain the error is in here:
$.ajax({
async: true,
url: '/reviews',
type: 'GET',
dataType: 'JSON',
success: function (data) {
$('.row[data-link=' + linked_entry + ']').remove();
$.each(data, function (index, item) {
var reviews_row = '<tr class="row" data-link="reviews">';
reviews_row += '<td>' + data.body + '</td>';
reviews_row += '<td>' + data.author + '</td>';
reviews_row += '<td>' + data.site + '</td>';
reviews_row += '<td style="text-align:center;"><input type="checkbox" name="isVisible" '+(data.isVisible ? 'checked' : '')+'></td>';
reviews_row += '</tr>';
$('.entry_table_container[data-link=' + linked_entry + ']').append(reviews_row);
});
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Change this:
$.each(data, function (index, item) {
To this:
$.each(data.reviews, function (index, item) {
and then:
item.body, item.author etc in your loop as one of the other contributors mentioned
I have a bunch of jQuery functions which gets JSON data from a MySQL database and displays it on certain pages within my application.
i have about 15 of these functions that look similar to the below and i would like to tidy them up and convert them to one major function which returns data based on the variables passed to the function. IE getdata(subscriptions) would display the subscriptions.
My issue is i'm not sure how to pass the column names to the function from the ajax query and remove the value.column-name from the function.
Example function from application
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value+
'</td><td>' + value.subscription_name +
'</td><td>' + value.subscription_cycle +
'</td><td>' + value.subscription_cost +
'</td><td>' + value.subscription_retail +
'</td><td>' + value.subscription_profit +
'</td><td>' + value.subscription_margin +
'</td><td>' + value.subscription_markup +
'</td></tr>';
});
$('#subscription-results').html(trHTML);
},
});
}
Any help is very much appreciated as i'm fairly new to jQuery
You can refer to this code:
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
$('#subscription-results').html(parseColumns(response));
},
});
}
function parseColumns(columns) {
var html = '';
if (Object.prototype.toString.apply(columns) === '[object Array]') {
$.each(columns, function(key, value) {
html += parseColumn(value);
})
} else {
html += parseColumn(columns);
}
function parseColumn(column) {
var trHTML = '<tr><td>' + column + '</td>';
for (var key in column) {
trHTML += '<td>' + column[key] + '</td>'
}
trHTML += '</tr>';
return trHTML;
}
return html;
}
i can get the json in the following format
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}]
how can i use the data to present like the image below, where the first line is username and second line is book
<button type="button" id="test">Test 123</button>
<ul id="studentList" data-role="listview" data-filter="true"></ul>
var serviceURL = "http://mydomain.com/";
var students;
$("#test").click(function()
{
getStudentList();
});
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
students = data.user_name;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.user_name + ' ' + student.password + '</h4>' +
'<p>' + student.user_name + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}
may i ask if the codes above correct?
you are naming response as data..since you response is in array [] you have to loop data first.. get its object which is data again ..
[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
//-^^^^---here
and get the correponding name and password object in the loop...you can get that by . operator.. so inside loop, student.data.user_name gives you username , student.data.book gives you book and similar for others...
try this...
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
//students = data.user_name;
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name +'</h4>' + //here get username
'<p>' + student.data.book + '</p>' + //here get book
'</li>');
});
$('#studentList').listview('refresh');
});
I have done it like that based on your input, you just need to include it into your code. I don't know what you mean by 'second line is book' since there is no book included in your json input + you are trying to access 'student.data.password' which is also not present in input.
Simple version of jsFiddle http://jsfiddle.net/2KMd9/
var json =[{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}},
{"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}];
var students = json;
$.each(students, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
So for your needs:
function getStudentList() {
$.getJSON(serviceURL + 'getStudents.php', function(data) {
$('#studentList li').remove();
$.each(data, function(index, student) {
$('#studentList').append('<li>' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</li>');
});
$('#studentList').listview('refresh');
});
}