Update partialview after Model updaton using Model popup - entity-framework

I have index page which contains 2 partial views.One for displaying Roles and another for displaying corresponding privileges.
#model IEnumerable<sample.Models.Role_Privilege_Map>
#{
ViewBag.Title = "RolePrivilgeMapping";
}
<h2>RolePrivilgeMapping</h2>
<script>
$(document).ready(function () {
registerTableClick();
//$("#tblRole tbody tr:first").trigger();
});
function registerTableClick() {
$("#tblRole tbody tr").on("click", function () {
$(this).siblings().removeClass('selected_row');
$(this).addClass("selected_row");
var roleId = parseInt($(this).find("td:eq(0)").text());
loadPrivilege(roleId);
});
function loadtrackPrivilege(roleId) {
$("#PrivilegeWrapper").load("#Url.Action("PrivilegesPartial", "RolePrivilegeMapping")",
{ 'roleID': roleId },
function (response, status, xhr) {
if (status == "error") {
alert("An error occurred while loading privileges.");
}
});
}
}
</script>
<div id="RolePrivilgeMappingWrapper">
<div class="float-left" id="roleWrapper">
#Html.Partial("_Role", sample.Models.DataProvider.DataProvider.GetRoleNames())
</div>
<div class="float-left" id="PrivilegeWrapper">
#Html.Partial("_Privilege", sample.Models.DataProvider.Provider.GetPrivilegeNames())
</div>
</div>
Here is my _Role.cshtml
#model IEnumerable<sample.Models.webpages_Roles>
#{
ViewBag.Title = "Index";
}
<script type="text/ecmascript">
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".editDialog").live("click", function (e) {
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Role',
autoOpen: false,
resizable: false,
height: 255,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>
<div class="settingsTable" style="position: relative; width: 100%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<h2>Role</h2>
</div>
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table id="tblRole">
<tr>
<th>
#Html.DisplayNameFor(model => model.RoleId)
</th>
<th>
#Html.DisplayNameFor(model => model.RoleName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.RoleId)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoleName)
</td>
<td>
#Html.ActionLink("Edit", "OpenEditRoleDialog", "RolePrivilegeMapping", new { id = item.RoleId }, new { #class="editDialog"}) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
<div id="dialog-edit" style="display: none">
</div>
</div>
On Role partial view I have edit link for every row displayed.
here is my _editrole.cshtml
#model sample.Models.webpages_Roles
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Ajax.BeginForm("EditRole", "RolePrivilegeMapping", new AjaxOptions { HttpMethod = "POST" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>webpages_Roles</legend>
#Html.HiddenFor(model => model.RoleId)
<div class="editor-label">
#Html.LabelFor(model => model.RoleName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Now while I click on edit link a jquery modal box gets displayed for editing details.I submit the changes asychronously as
#using (Ajax.BeginForm("EditRole", "RolePrivilegeMapping", new AjaxOptions { HttpMethod = "POST" }))
And the edit method is
public ActionResult EditRole(webpages_Roles webpages_roles)
{
if (ModelState.IsValid)
{
db.Entry(webpages_roles).State = EntityState.Modified;
db.SaveChanges();
}
return View("index");
}
My problem is
1. The dialog box is not getting closed. I have to manually click the cross
bar.
2. The Role partial view is not getting updated until I have to refresh the page.
I followed this link http://www.mindstick.com/Articles/279bc324-5be3-4156-a9e9-dd91c971d462/CRUD%20operation%20using%20Modal%20dialog%20in%20ASP%20NET%20MVC#.VVlyBLmqpHx

Related

How can I use v-for tag to show elements in the data?

I am creating ec mock-up, and how can I use v-for tag
developing environment
Mac, Vue.js, Atom, Server hostname is https://euas.person.ee/
Rigth Now↓
What I want to do is showing Order ID and Option Image for each row like
Order ID | OrderDescription | Action
1 "OptionImage" Detail Button
OrderListingVue
<template>
<div class="OrderListing">
<h2>My Orders</h2>
<table class="table">
<tr>
<th>OrderId</th>
<th>OrderDescription</th>
<th>Action</th>
</tr>
<tr v-for="(cart, order) in this.orders" :key="order.id">
<td>{{order}}</td>
<td>{{cart}}</td>
<td>
<b-button variant="dark" :to=" '/orders/' + order">Detail</b-button>
</td>
</tr>
</table>
</div>
</template>
<script>
import axios from "axios";
export default {
name: 'OrderListing',
props: {
order: Object
},
data: function() {
return {
orders: []
}
},
mounted() {
axios.get("https://euas.person.ee/user/orders")
.then(response => {
this.orders = response.data;
});
}
}
</script>
<style scoped>
.option-image {
max-height: 50px;
max-width: 100px;
}
</style>
Addition
ShoppingCartVue↓
<template>
<div class="shopping-cart-page">
<h2>ShoppingCart</h2>
<table class="table">
<tr>
<th>Product</th>
<th>Price</th>
<th>qty</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr v-for="(item, index) in this.items" :key="item.productId + '_' + index">
<td>
<img :src="item.optionImage" class="option-image" />
</td>
<td>{{ item.price }}</td>
<td>{{ item.qty }}</td>
<td>{{ item.total }}</td>
<td>
<b-button variant="danger" #click="removeItem(index)">Remove</b-button>
</td>
</tr>
<tr class="total-row">
<td>TOTAL:</td>
<td></td>
<td></td>
<td>{{ total }}</td>
<td></td>
</tr>
</table>
<b-button variant="success" size="lg" #click="orderNow" v-if="this.items.length">Order Now!</b-button>
</div>
</template>
<script>
import axios from "axios";
export default {
name: 'ShoppingCartPage',
computed: {
items: function() {
return this.$root.$data.cart.items || [];
},
total: function() {
let sum = 0
for (const item of this.items) {
sum += item.total
}
return sum
}
},
methods: {
removeItem: function(index) {
if (!this.$root.$data.cart.items) this.$root.$data.cart.items = []
this.$root.$data.cart.items.splice(index, 1);
console.log(this.$root.$data.cart.items);
this.$root.$data.saveCart();
},
orderNow: function() {
let data = this.$root.$data
axios.post("https://euas.person.ee/user/carts/" + this.$root.$data.cart.id + "/orders/",
this.$root.$data.cart).then(function() {
data.reinitCart();
})
}
}
}
</script>
<style scoped>
.option-image {
max-height: 50px;
max-width: 100px;
}
</style>
From what I understood you are looking for something like this:
<div v-for="order in orders" :key="order.id">
<div v-for="item in order.items" :key="item.productId">
<img :src="item.optionImage" class="option-image" />
</div>
</div>

How can I re-render the page after post request with react/redux?

There is a short time between the posting and the response from the server. How is it possible to cause your component to re-render when you get your positive response? I tried componentWillGetProps(){} and if-statements like
if(this.props.incomingItems){return: this.props.incomingItems}
but it none of them worked out. How did you solve this problem?
PS I'm using redux and axios for the requests.
import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import * as actions from '../../actions';
class eventView extends Component {
componentWillMount() {
this.props.eventView(this.props.params.eventID);
}
createNewRole(roleName){
this.props.createNewRole(roleName, this.props.params.eventID);
};
renderUsers(){
return this.props.eventDetails.userList.map((user)=>{
return(
<li className='list-group-item eventUserList' background-color="#f2f2f2" key={user._id}>
{user.userName}
</li>
);
});
};
deleteListItem(key){
const newKey = key.dispatchMarker.substr(44, 24);
this.props.RemoveRoleFromList(newKey)
this.props.fetchEvents();
}
renderRoles(){
return this.props.eventDetails.role.map((role)=>{
return(
<li className='list-group-item roleList' key={role._id}>
{role.roleName}
<img className="deleteListItem"
src="/img/trash.png"
key={role._id}
onClick={this.deleteListItem.bind(this)}/>
</li>
);
});
};
render() {
const { handleSubmit, fields: {eventName,location, eventPassword, roleName} } = this.props;
if(this.props.roleList){
console.log(this.props.roleList)
}
if (this.props.eventDetails){
return (
<div className='container-fluid'>
<div className="roleBox">
<form onSubmit={handleSubmit(this.createNewRole.bind(this))}>
<div>
<input {...roleName}
className="form-control roleBoxInputBar"
autoComplete="off"/>
<button className="RoleButton">Save</button>
</div>
<div className="listOfRoles">
<ul className="listOfRoles pre-scrollable">
{this.renderRoles()}
</ul>
</div>
</form>
</div>
<div>
<div>
<h1 className="eventName">
{this.props.eventDetails.eventName}
</h1>
</div>
<br/>
<table>
<tbody>
<tr>
<td className="eventViewTableLocation">Location:</td>
<td className="eventViewTable">{this.props.eventDetails.location}</td>
</tr>
<tr>
<td className="eventViewTableLocation">Date:</td>
<td className="eventViewTable">12/Feb/2018</td>
</tr>
<tr>
<td className="eventViewTableLocation">Time Left:</td>
<td className="eventViewTable">2 Days 2 Hours</td>
</tr>
</tbody>
</table>
</div>
<div className='eventViewUserBox'>
<h4 className="listOfUsers">Organisers:</h4>
<ul>
{this.renderUsers()}
</ul>
</div>
</div>
);
}else {
return (
<div>
</div>
);
}
}
}
function mapStateToProps(state) {
return { eventDetails: state.api.eventDetails };
return { roleList: state.api.roleList };
return { createdRole: state.api.createdRole };
}
export default reduxForm({
form: 'eventView',
fields: ['eventName', 'location', 'eventPassword', 'roleName']
}, mapStateToProps, actions)(eventView);
And my axios post goes something like this
export function createNewRole({roleName}, eventID){
return function(dispatch) {
axios.post(`${ROOT_URL}createRole/`+eventID, {roleName})
.then(response => {
if (response.data){
dispatch({
type: CREATED_ROLE,
payload: response.data,
});
};
})
.catch(response => dispatch(authError(response.data.error)));
};
};
Reducer:
export default function(state = {}, action) {
switch(action.type) {
case FETCH_ROLES:
return { ...state, roleList: action.payload };
case CREATED_ROLE:
return { ...state, createdRole: action.payload };
}
return state;
}
Thanks a lot!
function mapStateToProps(state) {
return { eventDetails: state.api.eventDetails };
return { roleList: state.api.roleList };
return { createdRole: state.api.createdRole };
}
This function always returns the first object. It should be:
function mapStateToProps(state) {
return {
eventDetails: state.api.eventDetails,
roleList: state.api.roleList,
createdRole: state.api.createdRole
};
}
I'm guessing roleList and createdRole are always undefined? Also it would be good if you would show the reducer.

kendo sortable widget mvvm UI glitch

I am using kendo's mvvm and sortable widget to allow a user to sort multiple tables with data binded to it. I have implemented the following code. It works, but the data seems to be logging correctly to the console. However, the data in the UI jumps around.
$(".sortable-handlers").kendoSortable({
handler: ".move",
hint:function(element) {
return element.clone().addClass("sortable-hint");
},
change: function(e) {
var services = viewModel.get("services");
console.log(e.oldIndex);
var oldIndex = e.oldIndex;
var newIndex = e.newIndex;
services.splice(newIndex, 0, services.splice(oldIndex, 1)[0]);
//Set it back to the original list
viewModel.set("services", services);
console.log(JSON.stringify(viewModel.get("services")));
}
});
It's been a long time but adding .trigger("change") works for me (I'm using jquery ui sortable instead of kendo ui sortable).
// Define model with dependent method
var MyModel = kendo.data.Model.define({
fields: {
left: "number",
right: "number"
},
total: function() {
return this.get("left") + this.get("right");
}
});
// Create view model
var viewModel = kendo.observable({
items: []
});
// bindings
kendo.bind($("#myView"), viewModel);
// using $.ui.sortable when list changes
var timeout = null;
viewModel.items.bind("change", function(e) {
clearTimeout(timeout);
timeout = setTimeout(function() {
$("#sortable").sortable({
update: function(e, ui) {
// get UID of sorting target
var targetUid = ui.item.attr("uid");
// list before
var beforeIndexes = _.map(viewModel.items, _.iteratee("uid"));
// target's original index
var fromIdx = _.indexOf(beforeIndexes, targetUid);
// list after
var afterIndexes = $("#sortable").sortable("toArray", {
attribute: "uid"
});
// target's new index
var toIdx = _.indexOf(afterIndexes, targetUid);
var changeItem = viewModel.items[fromIdx];
viewModel.items.splice(fromIdx, 1);
if (toIdx >= viewModel.items.length) {
viewModel.items.push(changeItem);
} else {
viewModel.items.splice(toIdx, 0, changeItem);
}
// refresh
viewModel.items.trigger("change");
}
});
}, 500);
});
// add some items to list
viewModel.items.push(new MyModel({
left: 1,
right: 2
}));
viewModel.items.push(new MyModel({
left: 6,
right: 3
}));
viewModel.items.push(new MyModel({
left: 5,
right: 7
}));
<link href="https://code.jquery.com/ui/1.12.0-beta.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.common.min.css" rel="stylesheet" />
<link href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.default.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2016.1.112/js/kendo.all.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id="myView">
<div class="k-grid k-widget">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>
<thead>
<tr>
<th class="k-header">SORTABLE</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="k-grid-content">
<table>
<tbody id="sortable" data-bind="source: items" data-template="template-item">
</tbody>
</table>
</div>
</div>
<div class="k-grid k-widget">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>
<thead>
<tr>
<th class="k-header">NOT-SORTABLE</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="k-grid-content">
<table>
<tbody id="sortable" data-bind="source: items" data-template="template-item">
</tbody>
</table>
</div>
</div>
</div>
<script type="text/x-kendo-template" id="template-item">
<tr data-bind="attr: {uid: uid}">
<td>
<span data-bind="text: left" />+
<span data-bind="text: right" />=
<span data-bind="text: total" />
</td>
</tr>
</script>

MVC binding list of object issue

Following my last post MVC model property null on posting form
and by looking in examples, I understand that when I need to post a
list from a view/partialView to the controller I should loop over the list and use
#HiddenFor property and on post, MVC can parse these fields into list.
Somehow the controller is not even been called, only when I remove these lines
#for (int i = 0; i < Model.To.Count; i++)
{
#Html.HiddenFor(m => m.To[i].UserName)
#Html.HiddenFor(m => m.To[i].FirstName)
#Html.HiddenFor(m => m.To[i].LastName)
}
the controller is being called but the sames problem occurs, my list is null.
My view:
#model Mobile.Models.MessageModel
<script type="text/javascript">
$(function () {
$('form').submit(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("message sent");
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
$("#BtnSuccessMsg").click();
},
error: function (xhr, textStatus, errorThrown) {
alert("message failed");
}
});
}
return false;
});
});
</script>
<table id="messages_panel_mbar" cellpadding="0" cellspacing="0">
<tr>
<td class="left_mbar">
</td>
<td class="main_mbar">
</td>
<td id="back_msg_details" class="right_mbar"></td>
</tr>
</table>
<div style="height:10%; width:100%; font: bold; font-size: 20px; text-align:right;"> #Html.Raw(Model.Subject)</div>
<div id="msg_chat" style="text-align:right; width:100%; height:auto; max-height:80%; overflow-y:scroll;">
#Html.Raw(Model.MsgHistory)
</div>
<div id="reply_msg" style="height: 5%">reply</div>
<div id="reply_msg_block" class="visible" style="width:100%; height:45%;">
#using (Ajax.BeginForm("ReplyMessage", "SettingsMenu", null, new AjaxOptions { }, new { #class = "center_form" }))
{
#Html.ValidationSummary(true, "");
<br />
<fieldset style="height:75%">
#Html.HiddenFor(m => m.Subject)
#Html.HiddenFor(m => m.ParentId)
#Html.HiddenFor(m => m.From)
#Html.HiddenFor(m => m.fullnamesender)
#for (int i = 0; i < Model.To.Count; i++)
{
#Html.HiddenFor(m => m.To[i].UserName)
#Html.HiddenFor(m => m.To[i].FirstName)
#Html.HiddenFor(m => m.To[i].LastName)
}
<div id="textarea_msg_reply">
#Html.TextAreaFor(m => m.Content, new { #class = "" })
#Html.ValidationMessageFor(m => m.Content)
</div>
</fieldset>
<input type="submit" value="send" />
}
</div>
My Controller :
[HttpPost]
public ActionResult ReplyMessage(MessageModel model)// List<Contacts> is empty
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
try
{
model.Send();
}
catch
{
throw new HttpException(404, "Error");
}
}
throw new HttpException(404, "Error");
}
Please advice! Thanks!
Ok, so I figured it out.
I was doing every fine except that the Contact class didn't have a parameterless constructor.
my view:
#model Mobile.Models.MessageModel
<script type="text/javascript">
function showMessagesPanel1() {
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
}
$('#back_msg_details').click(function () {
$.ajax({
url: '#Url.Action("Messages", "SettingsMenu")',
method: 'GET',
success: function (data) {
$("#messages_list").empty();
$("#messages_list").html(data);
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
}
});
})
$('#reply_msg').click(function () {
if ($("#reply_msg_block").is(":visible")) {
$('#msg_chat').animate({ height: '80%' });
// $("#reply_msg_block").slideUp().removeClass('visible');
}
else {
$('#msg_chat').animate({ height: '35%' });
}
$("#reply_msg_block").animate({ heigh: 'toggle' }, 350);
})
$(function () {
$('form').submit(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("message sent");
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
$("#BtnSuccessMsg").click();
},
error: function (xhr, textStatus, errorThrown) {
$('#reply_msg_block').html(xhr.responseText);
}
});
}
return false;
});
});
</script>
<table id="messages_panel_mbar" cellpadding="0" cellspacing="0">
<tr>
<td class="left_mbar">
</td>
<td class="main_mbar">
</td>
<td id="back_msg_details" class="right_mbar"></td>
</tr>
</table>
<div style="height:10%; width:100%; font: bold; font-size: 20px; text-align:right;"> #Html.Raw(Model.Subject)</div>
<div id="msg_chat" style="text-align:right; width:100%; height:auto; max-height:80%; overflow-y:scroll;">
#Html.Raw(Model.MsgHistory)
</div>
<div id="reply_msg" style="height: 5%">reply</div>
<div id="reply_msg_block" class="visible" style="width:100%; height:45%;">
#using (Ajax.BeginForm("ReplyMessage", "SettingsMenu", null, new AjaxOptions { }, new { #class = "center_form" }))
{
#Html.ValidationSummary(true, "");
<br />
<fieldset style="height:75%">
#Html.HiddenFor(m => m.Subject)
#Html.HiddenFor(m => m.ParentId)
#Html.HiddenFor(m => m.From)
#Html.HiddenFor(m => m.fullnamesender)
#for (int i=0; i<Model.To.Count; i++ )
{
#Html.HiddenFor(m => m.To[i].UserName)
#Html.HiddenFor(m => m.To[i].FirstName)
#Html.HiddenFor(m => m.To[i].LastName)
}
<div id="textarea_msg_reply">
#Html.TextAreaFor(m => m.Content, new { #class = "" })
#Html.ValidationMessageFor(m => m.Content)
</div>
</fieldset>
<input type="submit" value="send" />
}
</div>

Refresh datatable on Ajax success

I am using datatables and jquery dialog. Overall I have 3 forms and 3 datatables.
My script is working great but the thing I am struggling with is updating the correct datatable on success of ajax save (It doesn't even have to be the correct corresponding table, it could update all 3 tables on any of the 3 form saves.)
Any guidance would be greatly appreciated.
Page with buttons for showing datatable/forms in dialog
<div style="float:left;">
<button class="menubutton" id="view_academic">Academic</button>
<button class="menubutton" id="view_business">Business/Suppport</button>
<button class="menubutton" id="line_managers">Managers/Divisions</button>
<br/>
<br/>
</div>
<div style="float:right;">
Add Managers/Divisions
Add Academic
Add Business/Suppport
<br/>
<br/>
</div>
<div style="clear:both"></div>
<div id="academic_list">
<h2>Academic Entitlements</h2>
<table class="dataTable" id="academic_table" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr>
<th>Year</th>
<th>Employee</th>
<th>Division</th>
<th>Contract</th>
<th>Entitlement</th>
<th>Line Manager</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
<div id="business_list" class="the_options" style="display:none;">
<h2>Business & Manual Entitlements</h2>
<table class="dataTable" id="business_table" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr>
<th>Year</th>
<th>Employee</th>
<th>FT/PT</th>
<th>Weekly Hours</th>
<th>Division</th>
<th>Commencement</th>
<th>Entitlement</th>
<th>Line Manager</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="line_managers_list" class="the_options" style="display:none;">
<h2>Line Managers & Divisions</h2>
<table class="dataTable" id="line_managers_table" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr>
<th>Division</th>
<th>Name</th>
<th>Line Manager</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
</div>
initialise Datatables
$(function() {
// Implements the dataTables plugin on the HTML table
var $acTable= $("#academic_table").dataTable( {
"oLanguage": {
"sSearch": "Filter:"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/academic_serverside.php",
"iDisplayLength": 10,
"bJQueryUI": false,
"sPaginationType": "scrolling",
"sDom": '<"top"iflp<"clear">>rt>',
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true
});
});
$(function() {
// Implements the dataTables plugin on the HTML table
var $buTable= $("#business_table").dataTable( {
"oLanguage": {
"sSearch": "Filter:"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/business_serverside.php",
"iDisplayLength": 10,
"bJQueryUI": false,
"sPaginationType": "scrolling",
"sDom": '<"top"iflp<"clear">>rt>',
"sScrollX": "100%",
"sScrollXInner": "100%",
"bScrollCollapse": true
});
});
$(function() {
// Implements the dataTables plugin on the HTML table
var $lmTable= $("#line_managers_table").dataTable( {
"oLanguage": {
"sSearch": "Filter:"
},
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/line_managers_serverside.php",
"iDisplayLength": 10,
"bJQueryUI": false,
"sPaginationType": "scrolling",
"sDom": '<"top"iflp<"clear">>rt>'
});
});
$(document).ready(function() {
$(".the_options").hide();
});
Dialogs/datatables show/hide/open/close and AJAX save form:
$(document).ready(dialogForms);
function dialogForms() {
$('a.menubutton').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
submitFormWithAjax($(this).find('form'));
$(this).dialog('close');
$lmTable.fnDraw('');
},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
width: 600,
height: 500
});
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
$(this).dialog('close');
$lmTable.fnDraw('');
}
});
return false;
}
$(function() {
$("#add_academic")
.button()
.click(function() {
$("#academic-form").dialog( "open" );
});
$("#add_line_managers")
.button()
.click(function() {
$("#line-managers-form").dialog( "open" );
});
$("#add_business")
.button()
.click(function() {
$("#business-form").dialog( "open" );
});
$("#view_academic")
.button()
.click(function() {
$('#academic_list').show();
$('#business_list').hide();
$('#line_managers_list').hide();
});
$("#view_business")
.button()
.click(function() {
$('#academic_list').hide();
$('#business_list').show();
$('#line_managers_list').hide();
});
$("#line_managers")
.button()
.click(function() {
$('#academic_list').hide();
$('#business_list').hide();
$('#line_managers_list').show();
});
});
To update a table simply call fnDraw() on it. Since you are not using global variables, you must retrieve the table first
var $lmTable = $("#line_managers_table").dataTable( { bRetrieve : true } );
$lmTable.fnDraw();
EDIT - to show only the right table you could do something like:
function dialogForms() {
$('a.menubutton').click(function() {
var id = this.id;// Save the id of the clicked button
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
submitFormWithAjax($(this).find('form'), id);// Pass the id to the function
function submitFormWithAjax(form, id) {
form = $(form);
var table_id;
// Choose the table to display depending on the id, i made some guesses but adjust this
switch(id){
case 'view_academic': table_id = '#academic_table';
break;
case 'view_business': table_id = '#business_table';
break;
case 'line_managers': table_id = '#line_managers_list';
break;
}
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
$(this).dialog('close');
// Refresh table
var oTableToUpdate = $(table_id).dataTable( { bRetrieve : true } );
$oTableToUpdate .fnDraw();
// Hide all tables
$('table').hide();
// Show the refreshed
$(table_id).show();
}
});
return false;
}