Loading Ajax Data Dynamically - javascript

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

Related

Adding django view result from ajax as table in template

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/

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

Uncaught ReferenceError: x is not defined at HTMLTableRowElement.onclick

I've looked around for a solution but I might just be missing something really obvious because they don't solve my issue. I am no JS wiz at all, just a disclaimer.
I have an ASP project where JavaScript calls some C# code some times. I start my code with this:
window.onload = function () {
LiveSearch();
getCredentials();
getAllUsers();
getIsAdmin();
};
All of these functions work just fine. But the one of interest is getAllUsers() because it contacts the backend via an AJAX call to get some data to fill in a table.
function getAllUsers() {
var result_body = "";
$.ajax({
type: 'GET',
url: '/Home/GetAllUsers',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(""),
success: function (users) {
PushToScope("users", users);
var dict = scope[2];
if (dict.key.length > 0) {
for (var key in dict.value) {
result_body += '<tr onclick="getClickedUserObject(' + dict["value"][key].Initials + ')\">';
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Name + '</td>'
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Title + '</td>'
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Department + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].PrivatePhone + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkEmail + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkPhoneLandline + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkPhoneMobile + '</td>'
result_body += '</tr>';
}
} else {
result_body += '<tr>';
result_body += '<td style=\"col-xs-12\"><b>No Data. Try again, or Contact IT Support.</b></td>';
result_body += '</tr>';
}
$('#result-table').html(result_body);
}
});
}
Like I said, the above works, but the problem comes forth when I click an element in my table. "getClickedUserObject()" below:
function getClickedUserObject(lettercode) {
if (lettercode != undefined) {
var users = scope[2];
var user = users["value"][lettercode];
$('#result-title').html(user.Title);
$('#result-name').html(user.Name);
$('#result-department').html(user.Department);
$('#result-email').html('' + work.WorkEmail + '');
$('#result-work-mobile').html(user.WorkPhoneMobile);
$('#result-work-landline').html(user.WorkPhoneLandline);
$('#result-private-mobile').html(user.PrivatePhone);
if (lettercode == scope[0]) {
$("#HidePrivate").show();
$("#HidePrivate").disabled = false;
$("#HidePrivate").checked = user.HiddenPrivatePhone;
} else {
$("#HidePrivate").hide();
$("#HidePrivate").disabled = true;
}
}
return false;
}
This function never fires, instead I get the error in the title, saying that whatever lettercode I would get from clicking a row is not defined. This is odd to me because looking in the Google Chrome inspector I see this:
So what gives?
I'm not familiar with your function, but maybe the argument should be a string? Looks like you don't have any quotes around it in the function call.
Like so:
result_body += '<tr onclick=\"getClickedUserObject(\'' + dict["value"][key].Initials + '\')\">';

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN
function createCheckBoxPlatform(data) {
var platform = "";
$.each(data, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' + getOS();
});
$('#platform').append((platform));
}
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
I think you have to turn around your logic. The createCheckBoxPlatform loop will have completed before the getOS() ajax call returns, unless it's a synchronous call.
You could split the functions into pieces, gather the getOS data for each data point you have, then construct the checkboxes when your ajax call returns.
You can make your ajax call async and have to make no changes to your current logic. But your execution will stop till you don't get the callback to your ajax call.
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
async: true,
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value.
Maybe you could first, get the os list and then output what you need, like this:
function createCheckBoxPlatform(myDatas) {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (osList) {
var os = '<div>';
$.each(osList, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
$.each(myDdatas, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>'+os
});
$('#platform').append((platform));
}
});
}

Call function after some period time

I'm having a problem and don't know how to solve it. I have two functions in Javascript, both are called via AJAX, first function get values and insert records in DB and second function reads from DB and show the results. Since first function get values remotely sometimes response times are larger than second function and for that reason second function executes before first. What I need is to call buildTablesFromDB() only if AJAX call for buildClassification() is done. This is how my code looks like:
$(document).ready(function() {
function buildTablesFromDB() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/reader.php",
success: function(data) {
$("#clasification-data").html();
if (data.response === false) {
$(".alert").show();
$(".close").after(data.error);
} else {
if (data.html_content.position.length != 0) {
$("#clasification-holder").show();
var iterator = data.html_content.position;
var tr = "";
$.each(iterator, function(key, value) {
tr += "<tr>";
tr += '<td><img src="' + value.team_image + '" alt="' + value.team_name + '" title="' + value.team_name + '"> ' + value.team_name + '</td>';
tr += '<td>' + value.team_jj + '</td>';
tr += '<td>' + value.team_jg + '</td>';
tr += '<td>' + value.team_jp + '</td>';
tr += '<td>' + value.team_difference + '</td>';
tr += '<td><span class="glyphicon glyphicon-play"></span><span class="glyphicon glyphicon-stop"></span></td>';
tr += '</tr>';
});
$("#clasification-data").html(tr);
}
}
},
error: function() {
request.abort();
}
});
}
function buildClassification() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
// some error
}
},
error: function() {
request.abort();
}
});
}
window.setInterval(function() {
buildClassification();
}, 1800000); // Updates table results each 30 minutes
window.setInterval(function() {
buildTablesFromDB();
}, 1800000); // Updates table results each 30 minutes
buildClassification();
buildTablesFromDB();
});
How I can get this done?
you can call buildTablesFromDB() in the callback method of buildClassification()
e.g.
....
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
//
}else{
buildTablesFromDB();
}
},

Categories

Resources