How to update an HTML table through AJAX call? - javascript

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

Related

How to manually select an item using AJAX, Select2 and the "val" function

Trying to figure out how to change the selected item of a select2 box after the page loads for the first time (and after it has loaded data from a ajax api call)
I tried using the below, but I cant get them to call after the ajax data has loaded?
$series2.val('2');
$series2.trigger('change');
The documentation says that it cannot be done using the val function (see here https://select2.org/programmatic-control/add-select-clear-items) and I do not want to do this with a custom API call that provides a "selected" value - as this does not work with templating.
This is NOT a duplicate of Select2 auto trigger event change
var $make2 = $(".make2");
var $series2 = $(".series2");
$make2.select2().on('change', function() {
$series2.empty();
if ($make2.val() !== null) {
$.ajax({
url: "{{ url('/') }}" + "/api/series/" + $make2.val(),
type: 'GET',
dataType: 'json',
async: true,
success: function(data) {
$series2.select2({
data: data,
templateSelection: function(result) {
return result['text'];
},
templateResult: function(result) {
if (!result['id']) {
return result['text'];
};
var final =
'<div>' +
'<strong>' + result['text'] + '</strong>' +
'<ul class="list-unstyled">' +
'<li><em>' + result['make'] + '</em></li>' +
'<li><em>' + result['category'] + '</em></li>' +
'</ul>' +
'</div>';
return final;
},
escapeMarkup: function(result) {
return result;
},
});
}
});
}
}).trigger('change');
});

ASP.NET MVC slideshow - different views

I am working on a Health & Monitoring application which has several dashboards. Working on showing on all dashboards one by one as a slideshow. So that we know the health of the system without manual intervention.
This is what I did. Developed a view for slideshow Slideshow.cshtml and which has jquery code to connect to controllers and those controllers return partial views and partial views has code to connect to the server and display the data. So partial views are different dashboards. Tried to put it as simple as possible with the code. Sorry for the lengthy code.
I see dashboards are not displaying any data after sometime. I am looking for the suggestions and best practices and how to do it in a better way. are there any open source plug-ins we can use?
Slideshow.cshtml
<div id="partialContainer"></div>
$(function () {
getData();
setInterval(getData, 60000); // Iterate all pages 20 sec each page
});
function getData() {
getData1();
setTimeout(getData2, 20000); //20 Sec
setTimeout(getData3, 40000); //20 Sec
}
function getData1() {
$.ajax({
url: "#Url.Action("GetData1", "Dashboard")",
dataType: 'html',
success: function (data) {
$('#partialContainer').html(data);
}
});
}
function getData2() {
$.ajax({
url: "#Url.Action("GetData2", "Dashboard")",
dataType: 'html',
success: function (data) {
$('#partialContainer').html(data);
}
});
}
function getData3() {
$.ajax({
url: "#Url.Action("GetData3", "Dashboard")",
dataType: 'html',
success: function (data) {
$('#partialContainer').html(data);
}
});
}
****Controller:****
public class DashboardController : Controller
{
public ActionResult GetData1()
{
return PartialView("_Data1");
}
public ActionResult GetData2()
{
return PartialView("_Data2");
}
public ActionResult GetData3()
{
return PartialView("_Data3");
}
}
****One of the Dashboards(partial view): _Data1.cshtml****
<script>
$.ajaxSetup({
// Disable caching of AJAX responses */
cache: false
});
getDataP1();
function getDataP1() {
$("#tblErrors > tbody").html("");
$.ajax({
url: '#Url.Action("GetSummary", "Dashboard")',
data: {},
type: 'GET',
error: function () {
},
success: function (res) {
for (i = 0; i < res.Errors.length; i++) {
var data = res.Errors[i];
var rowClass = 'alt';
if (i % 2 == 0)
rowClass = '';
var row = "<tr class='" + rowClass + "'>";
//Appn Name
row = row + "<td>" + data.AppnName + "</td>";
//Application Type
row = row + "<td>" + data.ApplicationType + "</td>";
//Status
row = row + "<td>" + data.Status + "</td>";
row = row + "</tr>";
$("#tblErrors").append(row);
}
$("label[for='refreshTime']").html(res.LastRefreshTime);
}
});
}
</script>

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.

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

Cannot read property 'length' of undefined jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting a list from C# web method with ajax (code below), the list is returned fine, but after the success method is done, it gives me an error - (Cannot read property 'length' of undefined) in the jquery (screenshot below)
Am I missing something ??
function getMainParentMenus() {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
The method above is called by the below method.
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
// var parentMenus = getMainParentMenus();
getMainParentMenus();
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
};
EDIT :
the data in the alert in the first block of code above is displayed like so
and in the chrome debugger :
Because getMainParentMenus is using AJAX it is asynchronous. Your next line of code after calling getMainParentMenus will be executed before the .success part of your AJAX call, so it will be executed before parentMenuss has been populated.
There are a few ways you can tackle this, one way would be to pass the callback function to getMainParentMenus, something like this:
function getMainParentMenus(myCallback) {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
if (callback && typeof(callback)==="function") {
callback();
}
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
Now you can call it like this:
var html = "<div id='accordian'> ddd";
getMainParentMenus(function() {
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
});
Your code for rendering the menus is being executed immediately after getMainParentMenus(); Javascript does not wait for the ajax call to complete before moving on to the next block. It is operating asynchronously, as others have mentioned in the comments.
Your code has to wait for the ajax call to complete before trying to display the data.
jQuery supports deferred execution and promises, so you can create code that will not execute until other code has completed. This is the preferred way of handling asynchronous operations.
Try this:
function getMainParentMenus() {
var request = $.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
return request;
}
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
getMainParentMenus().success(function (result) {
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
});
}

Categories

Resources