I have this two ajax jquery function to add ,display and delete data from table the table ,delete works fine ut while adding the data gets saved but only gets displayed when i refresh ,how do i fix this?
<script type="text/javascript">
$(document).ready(function() {
(function ($) {z
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
console.log(JSON.stringify(data));
$.ajax({
type: "POST",
contentType: "application/json",
url: "createajaxuser",
data:JSON.stringify(data),
dataType: "json",
success: function(result) {
a
}
});
});
$.ajax({
url: 'listusersjson',
type: 'GET',
success: function(response) {
var trHTML = '';
var count =0;
$.each(response, function(i, item) {
console.debug("i is"+i);
var success="success";
var danger="danger";
var info="info";
var color ;
if(count==0)
{
color =success;
count++;
}else if(count==1){
color =danger;
count++;
}else{
color =info;
count=0;
}
trHTML += '<tr class="'+color+'" ><td>' + item.name + '</td><td>' + item.id + '</td><td>' + item.password + '</td><td>' + item.email+
'</td><td>' + '<button type="button" class="btn btn-danger" id="' + item.id + '" >Delete</button>'
'</td></tr>';
});
$('#delTable').append(trHTML);
$('button').click(function() {
var val = $(this).attr("id");
console.debug("saurabh userid", val);
var rowElement = $(this).parent().parent();
$.ajax({
type: "DELETE",
url: "ajaxuserr/"+val,
success: function(result) {
rowElement.find('td').fadeOut('3000',
function() {
rowElement.remove();
}
);
}
});
});
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<div>
<label for="name">Name</label> <input type="text" name="name"
id="name" />
</div>
<div>
<label for="email">Email</label> <input type="text" name="email"
id="email" />
</div>
<div>
<label for="password">Password</label> <input type="password"
name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
<div class="container">
<table class="table table-bordered table-hover" id="delTable">
<thead>
<tr>
<th width="100">Name</th>
<th width="100">ID</th>
<th width="100">Password</th>
<th width="100">Email</th>
<th width="100">Delete</th>
</tr>
</thead>
</tbody>
</table>
</div>
I am posting this answer because you are getting confused when I am tring to explain in comments,
So initially put your ajax call that builds the table tbody into a new Function like below.
function GetListOfUsers(){
$.ajax({
url: 'listusersjson',
type: 'GET',
success: function(response) {
var trHTML = '';
var count =0;
$.each(response, function(i, item) {
console.debug("i is"+i);
var success="success";
var danger="danger";
var info="info";
var color ;
if(count==0)
{
color =success;
count++;
}else if(count==1){
color =danger;
count++;
}else{
color =info;
count=0;
}
trHTML += '<tr class="'+color+'" ><td>' + item.name + '</td><td>' + item.id + '</td><td>' + item.password + '</td><td>' + item.email+
'</td><td>' + '<button type="button" class="btn btn-danger" id="' + item.id + '" >Delete</button>'
'</td></tr>';
});
$('#delTable tbody').append(trHTML); //Note I am trying to append into tbody you were directly appending to table without tbody
$('button').click(function() {
var val = $(this).attr("id");
console.debug("saurabh userid", val);
var rowElement = $(this).parent().parent();
$.ajax({
type: "DELETE",
url: "ajaxuserr/"+val,
success: function(result) {
rowElement.find('td').fadeOut('3000',
function() {
rowElement.remove();
}
);
}
});
});
}
});
});
}
And then you can call this method in the success method of the form submit ajax call. like below
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
console.log(JSON.stringify(data));
$.ajax({
type: "POST",
contentType: "application/json",
url: "createajaxuser",
data:JSON.stringify(data),
dataType: "json",
success: function(result) {
$('#delTable tbody').html(''); //empty the tbody
GetListOfUsers(); // call this function so that it rebuilds the tbody
}
});
});
Also since now we moved the ajax call that builds the tbody into a new function, you have to call this once in your initial script load. So that it builds up the tbody. So you can place this line of code after your form submit event handler
GetListOfUsers();
Related
My default start page has no data
Then filter out the data in the database after the two drop-down list
I hope that the filtered data can be displayed in pagination if there are more than ten records.
But I don't know how to do.
I'm new in this.
Here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
})
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('select'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('select'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedCity = $('#CITY option:selected').val();
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '#Url.Action("Getmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Mytable>tbody').empty();
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>'>+</td><td>' + data[i].ID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Address + '</td><td>' + data[i].Phone + '</td><td>' +'</td></tr>');
$('#Mytable>tbody').append(row);
}
$('#Mytable').show(); //show filter data
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
my dropdownlist is use js to connection
filter data also
that's means after user selected city and area
data will be displayed
here is my html:
<form>
<div class="row well">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">City</span>
<p>
#Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "Please select", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">Area</span>
<p> <select id="AREA" name="AREA"><option>Please select</option></select></p>
</div>
</div>
<div class="col-lg-2">
<button type="button" onclick="SearchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>search
</button>
</div>
</div>
<table id="Mytable" class="table table-bordered table-hover" style="display:none;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
//first page table will not show any data so is null
</tbody>
and my controller
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
string q = "Select * from Shopmap";
SqlDataAdapter da = new SqlDataAdapter(q, con);
da.Fill(dt);
}
return View(dt);
}
//js for first selected dropdownlist
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
//js for selected second dropdownlist then search data
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)
{
var b = new GetCollection();
List<Inserch> shop = b.GetDBdata();
var a = shop.FindAll(x => x.Address.Contains(cityName));
var Alldata = a.FindAll(x => x.Address.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Alldata);
}
I think it will use js to do what I want
then maybe c# code will put in
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)->this function
please tell me what to do
I desperately need.
thank's.
Pagination for Dropdownlist filter data in ASP.NET MVC
You can achieve that in following way:
HTML
<table id="userTable_info">
<thead>
<tr>
<th>Id </th>
<th>Controller </th>
<th>Page_name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
Script:
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#userTable_info').hide();
//On Submit Method
$("#Submit").click(function () {
var ddlCategory = parseInt($("#ddlCategory").val());
var ddlSubCategorie = parseInt($("#ddlSubCategorie").val());
$.ajax({
type: "POST",
url: 'http://localhost:5094/Member/GetShopmap',
dataType: "json",
data: { cityName: ddlCategory, areaName: ddlSubCategorie },
success: function (response) {
console.log(response);
$.each(response, function (index, value) {
var tr = "<tr>";
tr += "<td>" + value.ulogo_id + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.page_name + "</td>";
tr += "<td>" + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
$('#userTable_info').show();
}
});
});
});
</script>
}
Output:
Note: Based on your table defination please implement the neccessary chnages. It ill work as expected.
I am trying to provide a view where people will be able to create a list of categories and sub categories. Therefore I need to allow users to dynamically add Rows.
Each Row will allow user to add a category and then if they wish a Sub Category. For the first row I am able to use asp-items attributes to bind to a SelectList in my ViewBag, however when I add a new row via JS I cannot do it, I have tried 2 methods JS (both shown in the code):
1 - Storing the SelectList in a variable and looping through it
2 - Setting the asp-items to the SelectList
Does anyone know how I can populate my newly added rows? Also how would I bind the enetred in data to my Model; would it have to be done in the controller?
The code is as follows:
<script type="text/javascript">
$(document).ready(function () {
var categories = "#ViewBag.Categories";
var catOptions = '';
for (var i = 0; i < categories; i++) {
catOptions = catOptions + '<option value="' + categories[i].CategoryId + '">' + categories[i].Name + '</option>'
}
$(document).on("click", "#btnAddCat", function () {
var newCat =''+
'<tr class="categorieRows">' +
'<td colspan="2">' +
'<select>' +
catOptions +
'</select>' +
'</td>' +
'<td>' +
'<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>' +
'</td>' +
'</tr>';
$('#categoryTable').append(newCat);
});
$(document).on("click", "#btnAddSubCat", function () {
var newSubCat = '' +
'<tr class="categorieRows">' +
'<td></td>' +
'<td>' +
'<select asp-items="ViewBag.SubCategories"></select>' +
'</td>' +
'<td></td>' +
'</tr>';
$('#categoryTable').append(newSubCat);
});
});
</script>
#model IEnumerable<Categories>
#{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Surveys</h4>
<hr />
<table class="table table-striped" id="categoryTable">
<thead>
<tr>
<th>
Category
</th>
<th>
Sub Categories
</th>
<th>
<button type="button" id="btnAddCat" class="btn btn-xs btn-primary classAdd">Add Category</button>
</th>
</tr>
</thead>
<tbody>
<tr class="categorieRows">
<td colspan="2">
<select asp-items="ViewBag.Categories"></select>
</td>
<td>
<button type="button" id="btnAddSubCat" class="btn btn-xs btn-primary classAdd">Add Sub Category</button>
</td>
</tr>
</tbody>
</table>
<div>
<a asp-action="Index">Back to List</a>
</div>
Used Ajax calls to retrieve Categories data:
<script>
$(document).ready(function () {
$(document).on("change", "#selectCategroy", function () {
var subCat = this;
$.ajax({
url: "ReturnJsonSubCategories/?categoryId=" + $(subCat).val(),
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function (result) {
var categories = "";
$(result).each(function () {
categories = categories + '<option value="' + this.subCategoryId + '">' + this.name + '</option>'
});
var subCateList = $("#selectSubCategroy");
subCateList.empty();
subCateList.append(categories);
},
error: function (data) {
return "Error";
}
});
});
});
</script>
With the server side code looking like:
public JsonResult ReturnJsonSubCategories(int categoryId)
{
var jsonData = _context.SubCategories.Where(x => x.CategoryId == categoryId).ToList();
return Json(jsonData);
}
Similar with the last answer but a bit shorter
$(function () {
$('#CategoryId').change(function () {
$('#SubCategoryId').empty();
var url = '#Url.Content("~/")' + "api/CategoryApi/ListSubCategories";
$.getJSON(url, { categoryId: $('#CategoryId').val() })
.done(function (data) {
var subcategories = "";
$(data).each(function () {
subcategories += '<option value="' + this.CategoryId + '">' + this.Title + '</option>'
});
$('#SubCategoryId').append(subcategories);
})
});
});
and on server side
[HttpGet]
[Route("ListSubCategories")]
public IActionResult ListSubCategories(int categoryId)
{
var subCategories = _categorySvc.ListSubCategories(categoryId);
return Ok(subCategories);
}
When onclick the status update then only corresponding row should be refresh . before that i written the drop down onchange function based on that only table row is display.
cs.html:
<section class="card ">
<div class="card-block">
<h5 class="with-border m-t-lg">View Module List</h5>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label" for="exampleInput">Domain Name</label>
#Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { #class = "select2-arrow" })
</fieldset>
</div>
</div>
<br />
<div class="table-responsive" id="findValue" style="display:none;">
<table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
<thead>
<tr>
<th>S#</th>
<th>Module Name</th>
<th>Url</th>
<th>Roles</th>
<th>Action</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
Dropdown based on view tables code:
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
var Status = '';
if (item.Status == "Y") {
Status = '<img src="/img/Active.png" height="22" width="42"/>'
} else {
Status = '<img src="/img/InActive.png" height="22" width="42"/>'
}
var rows = "<tr>"
+ "<td>" + (i + 1) + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + ' ' + Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
Update status Code
<script>
$(document).ready(function () {
$("#example tbody").on('click', '.user-status', function () {
var getId = $(this).data('id');
var status = $(this).attr('data-status');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateStatusModule")',
dataType: 'json',
data: { ModuleID: getId },
success: function (data) {
if (data.success) {
alert(data.message);
$("#example tbody").load("/Account/UpdateStatusModule");
}
},
error: function (ex) {
alert('Failed to retrieve Sub Categories : ' + ex);
}
});
});
});
</script>
i written the drop down onchange function based on that only table row is display. When onclick the status update then only corresponding row should be refresh onchange no value should not be change
#region Update Status
[Authorize]
[HttpPost]
public ActionResult UpdateStatusModule(int ModuleID)
{
try
{
int refID = Convert.ToInt32(Session["RefID"]);
int typeID = Convert.ToInt32(Session["ComTypeID"]);
if (ModelState.IsValid && refID > 0)
{
userType type = new userType();
type.UpdateStatusModule(ModuleID);
}
return Json(new { success = true, message = "updated successfully" }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
#endregion
If you append html after the initialization it can't work.
You need to register events on document(without $(document).ready)
$(document).on("change","#DomainID", function () {
alert("domain changed");
}).on('click', '.user-status', function () {
alert("clicked");
});
For async POST:
$.post("MyUrl",{myId: myId},function(data){
do wathever
}).fail(function(x,y,z){
alert("ops");
});
More simple
I just want to ask how to get the selected value from appended select list using jquery. Please help me. Thanks in advance.
var wrapper1 = $(".column1");
array1 = ["sample1", "sample2", "sample3"];
var myRoot = window.location.origin + "/";
$.ajax({
url: myRoot + 'Payslip/GetDataFromAppend',
type: 'GET',
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ id: $this }),
async: true,
success: function (data) {
$(wrapper1).append(appendOption(data, array1[0]));
}
});
var appendOption = function (data, txtData) {
var appendfor = '<label class="col-sm-4 control-label"><label> ' + txtData + '...</label></label><div class="col-sm-7">' +
'<select class="form-control" asp-for="PayslipID" asp- items="ViewBag.PayslipID" data- val="true" data- val - required="The Payslip ID field is required." id= "PayslipID" >';
for (var i = 0; i < data.length; i++) {
console.log(data[i].value);
appendfor += '<option value="' + data[i].value + '">' + data[i].value + '</option>';
}
appendfor += '</select ></div >';
return appendfor;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group column1"></div>
The 'form-control' element is added to the page dynamically so you need to use event delegation, try this:
$(document).on('change', ".form-control", function(){
alert($(this).val())
});
'column1' should also work in place of 'document' assuming that it is a static element.
I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle