Adding django view result from ajax as table in template - javascript

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/

Related

Laravel: Variables showing as undefined when appending to table

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

Loading Ajax Data Dynamically

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;
}

Displaying data from json file

I'm trying to get content from a json file, but until now I get nothing.
I have the status connection == 200 and I can see the content in the chrome console
but I get nothing when I try to display the data to html table, but when I use the same jquery code with api from another service like import.io things works fine.
Can you tell me what am I doing wrong?
This api is from kimonolabs.
$(document).ready(function () {
var tabel = '<table><THEAD><caption>Calendário</caption></THEAD>';
tabel += '<th>' + 'Hora' + '</th>' + '<th>' + 'Equipas' + '</th><th>' + 'jornda' +
'</th><th>' + 'Data' + '</th>';
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/1dm6b',
dataType: 'json',
success: function (data) {
console.log(data);
$('#update').empty();
$(data.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td>' + '<td>' + this.golos + '</td></tr>';
}); //each
tabel += '</table>';
$("#update").html(tabel);
} //data
}); //ajax
}); //ready
According to JSON structure you should iterate over data.results.m_Marcadores array:
$(data.results.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td><td>' + this.golos + '</td></tr>';
});
Another problem. In header of the table you setup 4 colums, but in loop you are creating only two of them. Number of header columns should be the same as other row td.
Also you need to wrap th elements in tr. For example, fixed table header:
var tabel = '<table>' +
'<THEAD><caption>Calendário</caption></THEAD>' +
'<tr>' +
'<th>Hora</th><th>Equipas</th><th>jornda</th><th>Data</th>' +
'</tr>';
Demo: http://jsfiddle.net/onz02e43/

parse error from ajax call

I have written some ajax code using an open source library to do jquery pagination.
when the page first loads, it properly queries and displays the first 25 records from my database. But all subsequent requests fail with a parse error.
I can't see anything different between the formatting of data in the first page vs. other pages.
I've tried to use JSON Lint but none of my json passes, even the query for page 1.
My json data looks like this:
"[{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"and the final update\",\"number\":\"72212\",\"updatedname\":\"28112\",\"createdname\":\"conversion script\",\"user\":\"28507\",\"position\":\"1\",\"device_id\":\"2\",\"user_id\":\"2\",\"password\":\"Wh16dteaR\",\"updateddatetime\":\"2013-10-07 15:14:28\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"Bauer\",\"number\":\"72787\",\"createdname\":\"conversion script\",\"user\":\"28509\",\"position\":\"2\",\"device_id\":\"4\",\"user_id\":\"4\",\"password\":\"EHVOzIx1\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\" Woosly\",\"number\":\"72822\",\"createdname\":\"conversion script\",\"user\":\"28510\",\"position\":\"3\",\"device_id\":\"5\",\"user_id\":\"5\",\"password\":\"IP8rsdOE\"}]"
And then I use the parseJSON method to convert the above string into an object.
Here's the main routine that makes the ajax call and parses:
$.ajax({
url: mypath + '?startpos=' + page_index * items_per_page + '&numberofrecordstograb=' + items_per_page + '&viewtype=json',
dataType: 'json',
success: function(data){
data = $.parseJSON(data); //converting to a javascript object vs. just string...
if (data !=null) {
for(var i=0;i<data.length;i++){
var deviceobj = data[i];
newcontent = newcontent + "<TR>";
newcontent=newcontent + '<TD>';
//add EDIT hyperlink
if ($("#editdevicesettings").val() == "true") {
var temp = $("#editlinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]) + ' ';
}
//add DELETE hyperlink
if ($("#deletedevice").val() == "true") {
var temp = $("#deletelinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]);
}
newcontent=newcontent + '</TD>';
newcontent=newcontent + '<TD>' + deviceobj["number"] +'</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["user"] + '</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["password"] + '</TD>';
if (deviceobj["name"]) {
newcontent=newcontent + '<TD>' + deviceobj["name"] + '</TD>';
}
else {
newcontent=newcontent + '<TD> </TD>';
}
newcontent=newcontent + '<TD>' + deviceobj["description"] + '</TD>';
newcontent = newcontent + "</TR>";
}// end for
// Replace old content with new content
$('#Searchresult').html(newcontent);
}//end if
},
error: function(request, textStatus, errorThrown) {
console.log(textStatus);
},
complete: function(request, textStatus) { //for additional info
//alert(request.responseText);
console.log(textStatus);
}
});
// Prevent click eventpropagation
return false;
}//end pageselectCallback()
I'm not sure how to go about troubleshooting this.
Any suggestions would be appreciated
I decided to reduce the number of records returned to one per page... to narrow down the offending record.
now that I know which record it is, i should be able to resolve problem.

onclick shows duplicate json results inside view

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>');
});

Categories

Resources