Displaying data from json file - javascript

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/

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/

Adding a href to an Ajax generated table in html

I have implemented this with thymeleaf before and have struggled to implement it with javascript and Ajax get request.
Basically the table is generated and in my html script the Ajax get request gets and displays a list of teams into this table, is there a way to include a href or even a button after each row that passes the teams Id to my controller upon clicking the link?
Here is my controller:
$(document).ready(function() {
// DO GET
$.ajax({
type : "GET",
url : "/all",
success: function(result){
$.each(result, function(i, team){
var customerRow = ' <tr>' +
'<td>' + team.id + '</td>' +
'<td>' + team.teamName.toUpperCase() + '</td>' +
'<td>' + team.teamAddress + '</td>' +
'<td>' + team.level + '</td>' +
'<td>' + '' + View Team + '</td>' +
'</tr>';
$('#customerTable tbody').append(customerRow);
});
$( "#customerTable tbody tr:odd" ).addClass("info");
$( "#customerTable tbody tr:even" ).addClass("success");
},
error : function(e) {
alert("ERROR: ", e);
console.log("ERROR: ", e);
}
});
// do Filter on View
$("#inputFilter").on("keyup", function() {
var inputValue = $(this).val().toLowerCase();
$("#customerTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(inputValue) > -1)
});
});
})
You can see my attempt to implement it at the 5th <td> tag.
This will be the controller I am passing the id variable to, just incase.
#RequestMapping(value="/viewteam/{id}", method=RequestMethod.GET)
public String ViewTeam(Model model, #PathVariable Long id) {
Team team = teamRepository.findOne(id);
//the code below should ideally return all the players associated with the above team id in an array list, this array list will be passed via thymeleaf to display all players
model.addAttribute("team", team);
return "singleteam";
}
Looks like you may be over complicating this using the inline .Net syntax. Considering you already have the data back from the ajax you should be able to set the string (like #Musa mentioned) like this:
'<td>View Team</td>' +
Just as a robust example:
var team = {
id: 1,
teamName: "Capitals",
teamAddress: "Capital One Arena",
level: 9001,
};
var customerRow = ' <tr>' +
'<td>' + team.id + '</td>' +
'<td>' + team.teamName.toUpperCase() + '</td>' +
'<td>' + team.teamAddress + '</td>' +
'<td>' + team.level + '</td>' +
'<td>' + 'View Team</td>' +
'</tr>';
$('#customerTable tbody').append(customerRow);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customerTable">
<tbody>
</tbody>
</table>

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

How to apply style sheet on dynamic generate radio button?

here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');

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.

Categories

Resources