Json data on view not working MVC - javascript

Controller: In my controller I am getting data from sap b1if service.
I want to get json data from controller to view.
[HttpGet]
[AllowAnonymous]
public ActionResult Index()
{
ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_CALL_SYNC_XPT_INB_WS_CALL_SYNC_XPTipo_procClient B1ifSerPro
= new ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_CALL_SYNC_XPT_INB_WS_CALL_SYNC_XPTipo_procClient();
ServiceReference1.SelectQueryType request = new ServiceReference1.SelectQueryType();
request.Query = "Select TOP 1000 r.U_JobNr as U_JobNr,r.Code as Code,r.U_HlSQty as U_HlSQty,r.U_JobTp as U_JobTp,r.U_RDate as U_RDate,r.U_RTime as U_RTime,r.U_ASDate as U_ASDate,r.U_ASTime as U_ASTime,r.U_AEDate as U_AEDate,r.U_Lorry as U_Lorry,r.U_Driver as U_Driver,e.U_ZpCd as U_ZpCd,e.U_City as U_City,e.U_Phone1 as U_Phone1,e.U_SiteTl as U_SiteTl,r.U_ConNum as U_ConNum,r.U_CstWgt as U_CstWgt,r.U_Price as U_Price,r.U_TCTotal as U_TCTotal,r.U_SLicCh as U_SLicCh,r.U_PayMeth as U_PayMeth,r.U_JCost as U_JCost,r.U_RTimeT as U_RTimeT,r.U_SLicNr as U_SLicNr,r.U_VehTyp as U_VehTyp,r.U_IDHRTCD as U_IDHRTCD,r.U_IDHSEQ as U_IDHSEQ,r.U_CustRef as U_CustRef,r.U_Rebate as U_Rebate,r.U_WROrd as U_WROrd,r.U_WRRow as U_WRRow,e.U_Status as U_Status,r.U_RowSta as U_RowSta,r.U_LnkPBI as U_LnkPBI,r.U_AddCost as U_AddCost,r.U_AddCharge as U_AddCharge,r.U_ValDed as U_ValDed,e.U_PCardCd as U_PCardCd,e.U_SCardCd as U_SCardCd,r.U_OrdTot as U_OrdTot,r.U_PCTotal as U_PCTotal FROM[#IDH_JOBSHD] r ,[OCRD] bp ,[#IDH_JOBENTR] e WHERE r.U_JobNr = e.Code AND (r.U_CustCd = bp.CardCode Or (r.U_CustCd = '' AND r.U_ProCd = bp.CardCode)) ";
ServiceReference1.SelectQueryResponseType Response = B1ifSerPro.ZSelectQuery(request);
Response.SelectQueryResult.ToList();
//ServiceReference1.SelectQueryResponseTypeRow row = (ServiceReference1.SelectQueryResponseTypeRow)Response.SelectQueryResult.GetValue(1);
return Json(Response.SelectQueryResult.ToList(), JsonRequestBehavior.AllowGet);
//return Json("",JsonRequestBehavior.AllowGet);
}
My view as is follow:
JS is not working in my case. I want to get data as json form Controller and render in HTML using Bootstrap or simple will work.
#Model IEnumerable<BusinessLayer.OSM>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var osmlist;
$.ajax({
url:'#Url.Action("Index", "OSM")' , // '/OSM/Index/',
type: 'Get',
Data:{},
cache: false,
async: false,
DataType: 'Json',
success: function (data) {
osmlist = data;
var row = '';
$.each(data, function (i, item) {
row += "<tr>"
row += "<td>" + item.Code + "<td>"
row += "<td>" + item.U_JobNr + "<td>"
row += "<tr>"
$("#listRows tbody").html(row);
})
},
error: function (error) {
alert("Error : " + error.responseText);
}
});
});
</script>
<h2>Get OSM Rows</h2>
<table id="listRows" style="background-color: lightcoral">
#*<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Category</th>
<th>Price</th>
</tr>
</thead>*#
<tbody></tbody>
</table>
<hr />

Is it the typo error while putting the question here or you have forgotten to correctly close the tr and td tags in the javascript.

Related

Output JSON to html table

I'm having trouble outputting a JSON to a HTML table within my tab (for part of a javascript/jQuery evening course assignment).
Please could someone have a look, and advise what sort of amendments I would have to make to output in a table format?
I get the success alert, but the table doesn't populate.
Thanks.
// Tabs
$(function() {
$( "#tabs" ).tabs();
});
// Spanish
$(document).ready(function(){
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php", // path to file
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
success: function () {
alert('success');
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#table").append(row);
row.append($("<td>" + rowData.course + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.price + "</td>"));
}
And the HTML:
<div id="tabs">
<ol start="50">
<li>
Italian
</li>
<li>
Spanish
</li>
</ol>
<p id="tab-1"></p>
<p id="tab-2">
<table id='table'>
<thead>
<tr>
<th>Course</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</p>
<p id="tab-3"></p>
</div>
The main issue with your code was that you didn't call any function after the AJAX request completed successfully. You needed at least call drawTable() to populate the data.
However there are several improvements you can make to your code. Firstly, remove jsonp: 'callback'. It's the default value, and also redundant as you're supplying jsonpCallback. You can also then change jsonpCallback to 'drawTable'. This negates the need for the success handler function and means all the request data will be directly provided to your drawTable() function. Lastly, rather than creating DOM elements in memory and appending in each iteration of the loop it's much quicker to build a single string with all the table's HTML and append it once when finalised.
With all that said, try this:
$(document).ready(function() {
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
dataType: 'jsonp',
jsonpCallback: 'drawTable'
});
});
function drawTable(data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<tr><td>' + data[i].course + '</td><td>' + data[i].name + '</td><td>' + data[i].price + '</td></tr>';
}
$('#table tbody').append(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<thead>
<tr>
<th>Course</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Note that I reduced the HTML shown here to only the relevant parts.
// Tabs
$(function() {
$( "#tabs" ).tabs();
});
// Spanish
$(document).ready(function(){
$.ajax({
url: "http://learn.cf.ac.uk/ webstudent/sem5tl/javascript/assignments/spanish.php",
// path to file
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
// The var you put on this func will store data
success: function (data) {
alert('success');
// Call the function passing the data recieved
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#table").append(row);
row.append($("<td>" + rowData.course + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.price + "</td>"));
}

Updating the values attribute of a table inside a JSP page after an AJAX call

I have problem in displaying the content of a table which will be available once an AJAX request is made on click of some row of another table in the same page.
Following is my code for the table in my JSP page.
<table id="previousList" class="table">
<thead>
<tr>
<th colspan="6">Previous Billing Records</th>
</tr>
<tr>
<th>Bill Number</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<c:forEach var="lastBill" items="${previousBills}" varStatus="status">
<tr>
<td>${lastBill.billingId}</td>
<td>${lastBill.billAmount}</td>
</tr>
</c:forEach>
</tbody>
</table>
var jsonData;
var patientTable = $('#patientsList').DataTable();
var table = document.getElementById("selectedPatient");
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = response;
},
error: function(e) {
alert('Error: ' + e);
}
});
});
My controller code is as follows.
#RequestMapping(value="/lastBill")
public #ResponseBody String lastBill(ModelMap model, String patientId)
{
System.out.println("ID: " + patientId);
Gson gson = new Gson();
Bill b = new Bill();
b.setBillAmount(1000);
b.setBillingId("12345SDf");
Collection<Bill> bills = new ArrayList<Bill>();
bills.add(b);
model.addAttribute("previousBills",bills);
String jsonBills = gson.toJson(bills);
model.addAttribute("jsonBills", jsonBills);
return jsonBills;
}
I am able to get the JSON data but failed to bind the values to the table. Any suggestions/answers would be appreciable. Thanks in advance.
try this it should work.
var jsonData;
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = JSON.parse(response);
$.each(jsonData, function(i, bill) {
var newRowContent = "<tr><td>"+bill.billingId+"</td><td>"+bill.billAmount+"</td></tr>";
$("#previousList tbody").append(newRowContent);
});
},
error: function(e) {
alert('Error: ' + e);
}
});
});

How to send parameters to Action from javascript function?

I have a simple view that show a table of data, I want to sort one of its columns when the header is clicked by AJAX, I'm new to AJAX and JS, so this was my try in the view:
<table id="tbl" class="table">
<tr>
<th>
<a style="cursor: pointer" onclick="getData('desc')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</table>
#section scripts{
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
var srt = sort;
$.ajax({
type: 'GET',
url: '/Book/BooksData/' + srt,
dataTtype: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
</script>
}
but when I click the header the sort parameter goes null in the action,
public JsonResult BooksData(string sort)
{
var books = new List<Book>();
if (sort == "asc") books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
else books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
return Json(books, JsonRequestBehavior.AllowGet);
}
Yes I'm doing it wrong, but I revised it many times, I can't see logical error except that passing parameters in JavaScript is different than C#
Here is the simpliest way.You need to concatenate sort value to url, using query string.
Now, when you click header the sort parameter must goes with your value in the action.
Please try this:
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataType: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
Another way is to use this:
url: '#Url.Action("BooksData","Book")?sort=' + srt
The #Url.Action returns just a string.
In Razor every content using a # block is automatically HTML encoded by Razor.

How to update an HTML table through AJAX call?

Guys I have a html table in my ASP.net MVC home view. Now the table is being filled initially through the data present in model. Now upon clicking certain buttons on the homepage, I want to update the data present in the table i.e. clear the data present in the table and update it with the one from ajax call.
This is my table from view :
<article class="scrlable">
<table>
<tr>
<td>#</td>
<td>Name</td>
<td>Status</td>
<td>Since</td>
</tr>
#{
int srno = 1;
foreach (var pendingResponseModel in Model.hrPendingResponseList)
{
<tr>
<td>#srno</td>
<td>#pendingResponseModel.CandidateName</td>
<td>#pendingResponseModel.CandidateLifeCycleStatusName</td>
#if (pendingResponseModel.DayDifference == "1")
{
<td>#(pendingResponseModel.DayDifference) day</td>
}
else
{
<td>#(pendingResponseModel.DayDifference) days</td>
}
</tr>
srno++;
}
}
</table>
</article>
And this is my ajax call :
function GetStatusWise(control, departCode) {
$.ajax(
{
type: "GET",
url: "...URL..." + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data.data, function (index, value) {
// UPDATE TABLE HERE...
});
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}
The data returned from ajax call is in JSON. It has Name, Status and Since elements. They can be viewed by using value.CandidateName, value.Status etc
Now I want to update the values of above table with the values I am getting through AJAX call. How would I go about doing that? Is it possible to replace the whole article ?
Note : I am getting multiple values through ajax call so that is why I put a loop on the function.
I have solved my problem by the following code
function GetStatusWise(control, departCode) {
$.ajax(
{
type: "GET",
url: WebApiURL + ".....URL...." + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
var srno = 1;
$('#tblPendingHrResponse').find($('.trTblPendingHrResponse')).remove();
$.each(data.data, function (index, value) {
random(value, srno);
srno++;
});
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}
.
function random(values, srno) {
var daydifference = values.DayDifference == 1 ? '<td>' + values.DayDifference + ' day </td>' : '<td>' + values.DayDifference + ' days </td>';
var tr = '<tr class="trTblPendingHrResponse">' +
'<td>' + srno + '</td>' +
'<td>' + values.CandidateName + '</td>' +
'<td>' + values.CandidateLifeCycleStatusName + '</td>' +
daydifference + '</tr>' + srno++;
$('#tblPendingHrResponse').append(tr);
}
You can use jQuery append.
success: function (data) {
$.each(data.data, function (index, value) {
$("table").html("Your HTML to updated");
});
},
Have your controller method return a partial which contains your table or article.
[HttpPost]
public virtual ActionResult GetTable(ArticleViewModel viewModel)
{
// do stuff
return PartialView("_ArticleTable", viewModel);
}
Then update the table or article in jQuery:
ou can use jQuery append.
success: function (data) {
$("table").html(data);
},

Load table with updated data via ajax

I am developing a mobile app using Phonegap and jQuery Mobile. Basically for the first time when the app loads the data which gets populated using AJAX comes fine but It doesn't update.
Example: If there are 5 rows of data coming from the database and with some users action 1 more row has been added in the database but it still displays 5 rows. Currently it updates only if I exit app fully.
Also to solve this problem I have tried the following:
tbody.append(tableCells).load();
tbody.append(tableCells).trigger('create');
tbody.append(tableCells).trigger('refresh');
Any solution/idea how can I update it live or something without a user exits the app completely? Please see the below code.
Code:
HTML:
<table id="myPendingChallenges-table" width="100%">
<thead>
<tr>
<th>Game Type</th>
<th>Team Name</th>
<th>Initiator Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
to append rows inside the
JS: tbody.append(tableCells);
AJAX:
var currentUser = window.localStorage.getItem("currentUser");
user = JSON.parse(currentUser);
var username = user.username; //User name
//alert (username+', '+t_name+', '+formAction);
$.ajax({
type: 'POST',
url: 'http://www.example.com/webservice/index.php',
data: {username: username},
dataType : 'json',
success: function(data){
var json = JSON.stringify(data);
window.localStorage.setItem("teamChallenges", json);
challengePopulate();
},
error: function(){
alert('error!');
}
});
return false;
function challengePopulate()
{
var json = window.localStorage.getItem("teamChallenges");
var data = null;
if(!json)
data = JSON.stringify(window.teamChallenges);
var data = JSON.parse(json);
if(!data)
return;
var fields = ["game_type", "t_name", "ini_name"];
populatePCTable("#myPendingChallenges-table", fields, data);
}//end challengePopulate
function populatePCDTable(tableId, fields, data)
{
var tbody = $(tableId + " tbody");
var row = null;
for(var i in data) {
row = data[i];
if(!row)
continue;
var tableCells = "";
var fieldName = "";
for(var j in fields){
fieldName = fields[j];
teamName = row[fields[1]];
gameParam = row[fields[3]];
if(row[fieldName] == 'weighin'){
game_type = 'weighin';
row[fieldName] = '<img src="images/weightGame.png" width="100%" />';
}else if (row[fieldName] == 'activity'){
game_type = 'activity';
row[fieldName] = '<img src="images/activityGame.png" width="100%" />';
}
tableCells += "<td onClick=\"setPendingChallTitle('"+teamName+"');pendingchallengeDetails('"+teamName+"');\"><a href='#pendingChallengesDetailsPage'>"+row[fieldName]+"</a></td>";
}
tbody.append("<tr>" + tableCells + "<td onClick=\"ignorePendingChallenge(this,'"+teamName+"');\"><a href=''><img src='images/close_button.png' title='Ignore Challenge' /></a></td></tr>");
}
}//end function populatePCDTable

Categories

Resources