I need some help, I'm consuming a Web Api service from a MVC ASP.NET App using the jQuery' function $.ajax and need to retrieve a specific record from database, I can connect to the service and retrieve the correct value according to the id provided but I can manage to show the result in a table, I have checked the properties names and all is good, this is my javascript code
$("#boton_de_pabletoreto2").click(function () {
var id = $("#busqueda").val();
$.ajax({
type: "GET",
url: "http://localhost:55987/api/Empleado/"+ id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null)
{
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='id'>" + item.id + "</td>" +
"<td id='nombres'>" + item.Nombres + "</td>" +
"<td id='cargo'>" + item.Cargo + "</td>" +
"<td id='dpto'>" + item.Dpto + "</td>" +
"</tr>";
$('#Table').append(rows);
});
console.log(data);
}
else
{
alert("no se encontrarón datos");
}
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
});
and this is what it shows
I know that it retrieves a record because from the code got the due record in console
and this is the HTML code
<div class="panel panel-primary">
<div class="panel-heading">
$.ajax pabletoreto
</div>
<div class="panel-body">
ID: <input type="text" id="busqueda"><br /><br />
<table class="table table-bordered" id="Table">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Departamento</th>
<th>Cargo</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-md-2 offset-md-2"><button id="boton_de_pabletoreto">Obtener Todos</button></div>
<div class="col-md-1"><button id="boton_de_pabletoreto2">Búsqueda</button></div>
</div>
<br />
I use exactly the same code (except doesn´t need to provide the id value and the due url: "http://localhost:55987/api/Empleados") to retrieve all the records and it works
I know that it retrieves a record because from the code got the due record in console
Because you get only one record as a json object (not an array) the .each() iterates on each property (this is your issue....your undefined elements):
var data = {id: 1, Nombres: 'Pablo Ern...', Cargo: 'Gerente', Dpto: 'Contabi...'};
$.each(data, function (i, item) {
console.log('Item(' + i + '): ' + item);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In this case I suggest to avoid to loop and use directly the json object:
var item = {id: 1, Nombres: 'Pablo Ern...', Cargo: 'Gerente', Dpto: 'Contabi...'};
var rows = "<tr>" +
"<td id='id'>" + item.id + "</td>" +
"<td id='nombres'>" + item.Nombres + "</td>" +
"<td id='cargo'>" + item.Cargo + "</td>" +
"<td id='dpto'>" + item.Dpto + "</td>" +
"</tr>";
$('#Table').append(rows);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
$.ajax pabletoreto
</div>
<div class="panel-body">
ID: <input type="text" id="busqueda"><br/><br/>
<table class="table table-bordered" id="Table">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Departamento</th>
<th>Cargo</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-md-2 offset-md-2">
<button id="boton_de_pabletoreto">Obtener Todos</button>
</div>
<div class="col-md-1">
<button id="boton_de_pabletoreto2">Búsqueda</button>
</div>
</div>
<br/>
</div>
I think that you have wrong for each loop:
Change this:
$.each(data, function (i, item) { // Here is the error
var rows = "<tr>" +
"<td id='id'>" + item.id + "</td>" +
"<td id='nombres'>" + item.Nombres + "</td>" +
"<td id='cargo'>" + item.Cargo + "</td>" +
"<td id='dpto'>" + item.Dpto + "</td>" +
"</tr>";
$('#Table').append(rows);
});
With this:
$.each(data, function (item, i) {
var rows = "<tr>" +
"<td id='id'>" + item.id + "</td>" +
"<td id='nombres'>" + item.Nombres + "</td>" +
"<td id='cargo'>" + item.Cargo + "</td>" +
"<td id='dpto'>" + item.Dpto + "</td>" +
"</tr>";
$('#Table').append(rows);
});
The other error is that data is not a list of employees, is an employe. So you are iterating over an object, not a list. Change backend to send a list of employees instead an employe...
Related
I create table with print out data from database like this:
here the JS and HTML.
JS
function initDataTableSaldoRek1() {
showLoadingCss()
$.ajax({
url: baseUrl + "api_dashboard/get_ivest",
dataType: 'JSON',
type: "GET",
success: function (res) {
var data = res.return;
$("#date").html(data[0].TANGGAL);
$('#table-invest tbody').empty();
$.each(data, function (key, val) {
var html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD,2,".",",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR,2,".",",") + "</td>" +
"</tr>";
$('#table-invest tbody').append(html);
});
hideLoadingCss()
},
});
}
HTML
<div class="view-table" >
<table id="table-invest" class="table table-bordered">
<thead>
<tr>
<th style="background-color: #67a2d8" width="12.5%">DATE</th>
<th style="background: #67a2d8" width="12.5%">TYPE OF PAYMENT</th>
<th style="background: #67a2d8" width="12.5%">EUR</th>
<th style="background: #67a2d8" width="12.5%">USD</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
and i want add a row every 3 rows that sum column 2 & 3 as below .
Everybody in here have ever experience to create table as below before in JavaScript?
Thank you..
Just make a check on each third row, since the $.each callback provides an index value.
function initDataTableSaldoRek1() {
showLoadingCss()
$.ajax({
url: baseUrl + "api_dashboard/get_ivest",
dataType: 'JSON',
type: "GET",
success: function (res) {
var data = res.return;
$("#date").html(data[0].TANGGAL);
let html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD, 2, ".", ",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR, 2, ".", ",") + "</td>" +
"</tr>";
$('#table-invest tbody').append(html);
$('#table-invest tbody').empty();
$.each(data, function (key, val) {
if ((key+1) % 3 === 0 ){
html = `<tr><td>TOTAL</td></tr> ${html}`;
}else{
return html;
}
});
hideLoadingCss()
},
});
}
You can simply use a counter, when this counter reaches the amount of rows you want, add the "total" row and reset the counter.
Also, keep track of the total value (I don't know which total you want to calculate, so it is up to you this part), inside the if to check the counter, reset this total too.
Something like this:
let counter = 0;
let sumTotal = 0;
$.each(data, function(key, val) {
var html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD, 2, ".", ",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR, 2, ".", ",") + "</td>" +
"</tr>";
sumTotal = 0;//USE YOUR LOGIC TO CALCULATE AND INCREASE TOTAL
$('#table-invest tbody').append(html);
counter++;
//check if it is the moment to add the new row total
if (counter == 3){
let newRow = "<tr>" +
"<td>Total: " + sumTotal + "</td>" +
"</tr>";
$('#table-invest tbody').append(newRow);
counter = 0;
sumTotal = 0;
}
});
As shown in Image I have 20 Records in Table1 And 7 in Table2 if I want to Show result like result table against UserID.
and show the result into view from database.
my view code is
<div class="tblContainer">
<table class="table table-striped table-bordered " id="TblRole" cellspacing="0" align="center">
<thead>
<tr>
<th>Roles</th>
<th>CreateAccess</th>
<th>ViewAccess</th>
<th>EditAccess</th>
<th>ReportAccess</th>
</tr>
</thead>
<tbody></tbody>
</table>
and I got the data in jsUsers script is
function SearchUser() {
var EmpCode = $('#EmpCode').val()
alert("Call");
$.ajax({
type: "POST",
url: "/Roles/GetUserRoleInformation",
data: '{ EmpCode: "' + EmpCode + '" }',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
if (data.jsUsers != null) {
alert("User Alredy Exist in FastTrack.");
var rows;
$.each(data.jsUsers, function (i, item) {
rows += "<tr>"
+ "<td>" + item.RoleName + "</td>"
+ "<td>" + item.CreateAccess + "</td>"
+ "<td>" + item.ViewAccess + "</td>"
+ "<td>" + item.EditAccess + "</td>"
+ "<td>" + item.ReportAccess + "</td>"
+ "</tr>";
});
$('#TblRole').append(rows);
}
else {
alert("User Not Created yet.");
}
},
});
}
Please Help to solve this problem.
Try this:
SELECT B.`UserID`, A.`RoleID`, A.`RoleName`, B.`Create`, B.`View`, B.`Edit`
FROM `Table1` A
LEFT JOIN `Table2` B ON A.`RoleID` = B.`RoleID` AND B.`UserID` = 1
Updated Answer:
Simply use your input value as UserID:
SELECT 1 AS `UserID`, A.`RoleID`, A.`RoleName`, B.`Create`, B.`View`, B.`Edit`
FROM `Table1` A
LEFT JOIN `Table2` B ON A.`RoleID` = B.`RoleID` AND B.`UserID` = 1
Otherwise if you pass the UserId as parameter.
Then use the parameter:
SELECT #ParamValue AS `UserID`, A.`RoleID`, A.`RoleName`, B.`Create`, B.`View`, B.`Edit`
FROM `Table1` A
LEFT JOIN `Table2` B ON A.`RoleID` = B.`RoleID` AND B.`UserID` = #ParamValue
I am trying to populate an html table of JSON data. I was provided the JSON data and cannot determine why it isn't populating but suspect the JSON may not be formatted properly. When I use other sample data it works, then when I sub in the JSON I was provided it doesn't work. I've tried copying the JSON into a file on my direct server, linking to what I was provided (here: https://boiling-fortress-75456.herokuapp.com/) and inserting it on myjson.com and reformatting the JSON data.
Here is my code:
<script>
$(function() {
var entries = [];
var dmJSON = "https://api.myjson.com/bins/6sjud?callback=?";
$.getJSON(dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.rank + "</td>" + "<td>" + f.name + "</td>" + "<td>" + f.march_rank + "</td>" + "<td> " + f.april_rank + "</td>" + "<td>" + f.may_rank + "</td>" + f.personal_volume + "</td>" + f.team_volume + "</td>" + "</tr>"
$(tblRow).appendTo("#incentive tbody");
});
});
});
</script>
<div class="wrapper">
<div class="profile">
<table id= "incentive" border="1">
<thead>
<th>Rank</th>
<th>Name</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>Highest Rank</th>
<th>Personal Volume</th>
<th>Team Volume</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
You need to get the objects from affiliate
$.each(data.affiliate, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.rank + "</td>" + "<td>" + f.name + "</td>" + "<td>" + f.march_rank + "</td>" + "<td> " + f.april_rank + "</td>" + "<td>" + f.may_rank + "</td>" + f.personal_volume + "</td>" + f.team_volume + "</td>" + "</tr>"
$(tblRow).appendTo("#incentive tbody");
});
Response from service
{
"affiliate":[{
"rank":1,"name":"Sally","march_rank":"Gold","april_rank":"Silver","may_rank":"Silver","highest_rank":"Silver","team_volume":12345
},{
"rank":2,"name":"Zelda","march_rank":"Gold","april_rank":"Bronze","may_rank":"Silver","highest_rank":"Gold","team_volume":12345
}
]
}
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var entries = [];
var dmJSON = "http://crmfrdev.eu-gb.mybluemix.net/Cordova_Select.jsp?callback=?";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.Store_Media_Id + "</td>" + "<td>" + f.Store_Name + "</td>" + "<td>" + f.Store_ID + "</td>" + "</tr>"$(tblRow).appendTo("#entrydata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
<th>STORE MEDIA ID</th><th>STORE NAME</th><th>STORE ID</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
First of all, ensure that you allow cross origin when the engine renders your page (see this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin)
Second, you code is broken. Have this:
$(function() {
var entries = [];
var dmJSON = "http://crmfrdev.eu-gb.mybluemix.net/Cordova_Select.jsp?callback=?";
$.getJSON(dmJSON, function(data) {
$.each(data, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.Store_Media_Id + "</td>" + "<td>" + f.Store_Name + "</td>" + "<td>" + f.Store_ID + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
I am making a live data portal in which I have to display live data using Ajax in asp.net using c#.
I have one table and a div which contains data but in different way/different style.
Every time my page loads after 4 secs of time to show updated data i.e table and div both refreshes to have updated data.
Initially when page loads first time, I have displayed table to show data and hiden the data which is in div's form, if I clicked button(toggle button) it will display data in div's form and hide table data.
Now problem is that when I clicked toggle button it does not display's data in div form but it reloads whole java script
and display data in table every time when I clicked the button.
I want to toggle between table and a div.
Below I have my code what I have done so far.
Please help me what I have done wrong.
Thank You.
Note Data comes from db which is SQL.
<form id="form1" runat="server">
<div id="container">
<table id="liveData">
</table>
<div id="div_f" style="display:none;">
<%--<table id="liveData_div"></table>--%>
</div>
</div>
<button>Toggle Data</button>
</form>
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery-2.1.4.js"></script>
<script>
(function worker() {
$.ajax({
type: "POST",
url: "Default2.aspx/BindData",
contentType: "application/json;charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
//alert("Hello");
$("#liveData").empty();
if (data.d.length > 0) {
InDivs(data);
$("#liveData").append("<tr><th>Node Id</th><th>Parent</th><th>Voltage</th><th>Humid</th><th>HumTemp</th><th>PrTemp</th><th>Pressure</th><th>Light</th><th>Accel_X</th><th>Accel_Y</th><th>result_time</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#liveData").append("<tr><td>" +
data.d[i].nodeID + "</td><td>" +
data.d[i].parent + "</td> <td>" +
data.d[i].voltage + "</td><td>" +
data.d[i].humid + "</td> <td>" +
data.d[i].humtemp + "</td><td>" +
data.d[i].prtemp + "</td> <td>" +
data.d[i].press + "</td><td>" +
data.d[i].light + "</td> <td>" +
data.d[i].accel_x + "</td><td>" +
data.d[i].accel_y + "</td><td>" +
data.d[i].result_time + "</td></tr>");
}
}
// Nontoggle();
},
error: function (result) {
//Handling error
alert("error");
},
complete: function () {
// Schedule the next request when the current one's complete
setTimeout(worker, 4000);
}
});
})();
function InDivs(data) {
$("#div_f").empty();
if (data.d.length > 0) {
//$("#liveData").append("<tr><th>Node Id</th><th>Parent</th><th>Voltage</th><th>Humid</th><th>HumTemp</th><th>PrTemp</th><th>Pressure</th><th>Light</th><th>Accel_X</th><th>Accel_Y</th><th>result_time</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#div_f").append(
"<table class='LiveData_div'><tr>" +
"<td>Node Id</td>" +
"<td>" + data.d[i].nodeID + "</td>" +
"<td>Parent Id</td>" +
"<td>" + data.d[i].parent + "</td>" +
"</tr>" +
"<tr>" +
"<td>Voltage</td>" +
"<td>" + data.d[i].voltage + "</td>" +
"<td>Humid</td>" +
"<td>" + data.d[i].humid + "</td>" +
"</tr>" +
"<tr>" +
"<td>Hum Temp</td>" +
"<td>" + data.d[i].humtemp + "</td>" +
"<td>Press</td>" +
"<td>" + data.d[i].press + "</td>" +
"</tr>" +
"<tr>" +
"<td>Press Temp</td>" +
"<td>" + data.d[i].prtemp + "</td>" +
"<td>Light</td>" +
"<td>" + data.d[i].light + "</td>" +
"</tr>" +
"<tr>" +
"<td>Accel_x</td>" +
"<td>" + data.d[i].accel_x + "</td>" +
"<td>Accel_y</td>" +
"<td>" + data.d[i].accel_y + "</td>" +
"</tr>" +
"<tr>" +
"<td>Time</td>" +
"<td>" + data.d[i].result_time + "</td>" +
"</tr></table>");
}
}
}
$(function () {
$('button').live('click', function () {
$('#div_f').toggle();
$('#liveData').toggle();
});
});
</script>
Problem
Your page reload since the button tag has by default type='submit' and that will refresh the page.
Solution
You should define your type as type='button' to prevent that behavior, e.g :
<button type='button'>Toggle Data</button>
Hope this helps.
Try to add a "return false;" at the end of your click button:
$('button').live('click', function () {
$('#div_f').toggle();
$('#liveData').toggle();
return false;
});