I have a page that looks like this:
"Default List Name" is the name of the current page displayed. There are two buttons below and then a table which is the Default List table. Once I click Btn1, it will just re-display the default list table, but when I click Btn2, another table will be displayed, replacing the default list table. Let's call the second table "Second List". Once the table changes, the title "Default List Name" will also change to "Second List Name".
I am going to use AJAX for this so that real time button click and displaying of the corresponding table are applied. But I am still new to AJAX so I am having quite a hard time.
Here's my current code:
var title = $("#title").text();
var btn1 = $("#btn1");
var btn2 = $("#btn2");
/** If one of the buttons is clicked after another and then displays a table, the previous ajax that displayed the previous table, will be removed **/
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList(){
console.log("display default list table");
/*$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'url to current page (not sure)',
async: false
}).*/
}
function displaySecondList(){
console.log("display second list table");
}
I hope I'm making my self clear and hope you guys can help me.
I just wrote this for you just to show you that you can always show and hide your tables
$(document).ready(function(){
$("#mytable1").show();
$("#mytable2").hide();
$("#button1").click(function(){
$("#text").html("Default List Name");
$("#mytable2").hide();
$("#mytable1").show();
});
$("#button2").click(function(){
$("#mytable1").hide();
$("#mytable2").show();
$("#text").html("Second List Name");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id = "text">Default List Name</div>
<button id = "button1">Button1</button>
<button id = "button2">Button2</button>
<table id = "mytable1" border = "1">
<tr>
<td>text1</td>
<td>text1</td>
<td>text1</td>
</tr>
<tr>
<td>text2</td>
<td>text2</td>
<td>text2</td>
</tr>
<tr>
<td>text3</td>
<td>text3</td>
<td>text3</td>
</tr>
<tr>
<td>text4</td>
<td>text4</td>
<td>text4</td>
</tr>
</table>
<br/>
<table id = "mytable2" border = "1">
<tr>
<td>box1</td>
<td>box1</td>
<td>box1</td>
</tr>
<tr>
<td>box2</td>
<td>box2</td>
<td>box2</td>
</tr>
<tr>
<td>box3</td>
<td>box3</td>
<td>box3</td>
</tr>
<tr>
<td>box4</td>
<td>box4</td>
<td>box4</td>
</tr>
</table>
NOW for your ajax, you should just simply hide one of the tables based on the button that was clicked, and then load the data to your specific table. This works for me. Hope it helps :)
Here's AJAX:
$(document).ready(function(){
$("#button1").click(function(){
$("#mytable2").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable1").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
$("#button2").click(function(){
$("#mytable1").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable2").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
});
I created this fiddle for you: https://jsfiddle.net/8bakcfub/.
Basically, each button click will simulate a call to an API that returns a very simple JSON object. On success, the code parses the response, empties the table and appends a new row to it with the data, and finally changes the title.
Note that the code is pretty much the same for both buttons, except for (a) the JSON returned from AJAX, and (b) the title :)
HTML:
<p id="title">
This title will be replaced...
</p>
<button id="btn1">
First list
</button>
<button id="btn2">
Second list
</button>
<table id="table">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
<tbody>
</tbody>
</table>
JS:
var btn1 = $("#btn1");
var btn2 = $("#btn2");
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
row: [1, 2]
})
},
success: function(result) {
$('#title').text('first list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
function displaySecondList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
'row': [3, 4]
})
},
success: function(result) {
$('#title').text('second list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
Related
I have created a Method GetOpPriv() in the Home Controller which retrieves a JSON from a stored procedure.
I have two tables on the Index View id='table1' & 'table2'
I have Displayed the JSON values on 'table1' using JQuery Ajax.
Now, I want to select rows from table1 and send those JSON values to table2 on click of a button.
On click of 1st button, the value should be sent to table2 and the same value should be spliced from table1 and vice versa for the 2nd button.
How can I do the Push and splice at the same time?
Home Controller
public JsonResult GetOpPriv()
{
using (MvcAssignmentEntities db = new MvcAssignmentEntities())
{
var op =( from data in db.OPERATION_PRIVILEGE()
select new
{
OperationName = data.OperationName,
PrivilegeName = data.PrivilegeName
}).ToList();
return Json(op, JsonRequestBehavior.AllowGet);
}
}
JQuery Ajax
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr><td>" + item.PrivilegeName + "</td>" + "<td>" + item.OperationName + "<td>";
});
$("#table1").html(row);
},
error: function (result) {
alert("Error");
}
})
});
</script>
<caption class="display-4">Available Privilege:</caption>
<table class="table-bordered" style="float: left" id="table1">
<thead>
<tr>
<th>Operation </th>
<th>Privilege Name</th>
</tr>
<tbody></tbody>
</table>
I have a datatable that use two Ajax Calls to load data in it. I was following demo here JSFiddle
I'm trying to get from the first Ajax call all data about replies, and load them in the parent row.
then I'm trying to get from the second Ajax call all attachments related to the reply, by reply id, so I want to get in each parent row (reply id, and other data related to the reply), and I want to get in the child row all attachments related to this particular (reply id) , [for now I'm using fileName for loading the attachments]
so the table will load all replies, and when the user click on the first "td" to open the child row, the user must see only attachments that are related to this reply, and when the user open another child row , will see different attachment, which are related only to the reply that he clicked on its "td"
my problem is with the child row, it doesn't load anything, and when I put fixed id in the ajax call, it load same files in all child rows, but I don't want that, I want each child row to load only related attachments (attachments by reply id)
I spent 5 days trying , but I couldn't solve it, and also I didn't find any similar problem in the net that can help.
is it possible to achieve what I want using datatable?
here is my HTML code
<table id="replyTable" class="display table-bordered nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Attachments</th>
<th>Reply ID</th>
<th>Ticket ID</th>
<th>Message</th>
<th>Transaction Status</th>
<th>Created Date</th>
</tr>
</thead>
<tbody></tbody>
</table>
here is my JS code
<script>
$(document).ready(function () {
var TicketID = $("#txtTicketID").val();
var table = $('#replyTable').DataTable({
ajax: {
type: "GET",
url: "/api/TicketsReplies/GetTicketsRepliesByTicketID/" + TicketID,
dataSrc: "",
datatype: 'json',
cache: false,
},
columns: [
{
className: "details-control",
orderable: false,
defaultContent: ""
},
{
className: "replyIdClass",
data: "id",
},
{ data: "ticketsId" },
{ data: "message" },
{ data: "transactionStatus.nameEnglish" },
{ data: "createdDate" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#replyTable').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#replyTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
format(row.child);
tr.addClass('shown');
}
});
function format(callback) {
var IdValue = $('#replyTable').find('.replyIdClass').text();
$('.replyIdClass').each(function (i) {
var repId = $(this).text();
$.ajax({
url: '/api/TicketAttachmentApi/GetRepliesAttachments/' + repId,
dataType: "json",
complete: function (response) {
var data = JSON.parse(response.responseText);
console.log(data);
var tbody = '';
$.each(data, function (i, d) {
tbody += '<tr><td>' + d.fileName + '</td><td>' + d.id + '</td></tr>';
});
console.log('<table>' + tbody + '</table>');
callback($('<table>' + tbody + '</table>')).show();
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
});
}
});
</script>
Finally after 4 days trying, I could solve the problem, after better understanding how the datatable and child row work, so I would like to put my solution here, so maybe I can benefit others who have same problem.
well the problem here is using foreach in format function to get the replies ids, it is wrong, I must pass the reply id from the child row where I clicked the cell, to the format function and retrieve only the attachment where the reply id = the reply id in the cell where I clicked
here is my solution, it is working perfectly.
This is the HTML
<input type="hidden" value='#ViewContext.RouteData.Values["id"]' id="txtTicketID" />
<table id="replyTable" class="display table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Attachments</th>
<th>Reply ID</th>
<th>Message</th>
<th>Transaction Status</th>
<th>Created Date</th>
</tr>
</thead>
<tbody></tbody>
</table>
here is the Ajax and jQuery code
<script>
$(document).ready(function () {
var TicketID = $("#txtTicketID").val();
// Get Replies From API by TicketID
var table = $('#replyTable').DataTable({
ajax: {
type: "GET",
url: "/api/TicketsReplies/GetTicketsRepliesByTicketID/" + TicketID,
dataSrc: "",
datatype: 'json',
cache: false,
},
columns: [
{
className: "details-control",
orderable: false,
defaultContent: ""
},
{
className: "replyIdClass",
data: "id",
},
{
data: "message",
},
{ data: "transactionStatus.nameEnglish" },
{ data: "createdDate" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#replyTable').on('click', 'td.details-control', function () {
var id = $(this).closest("tr").find('.replyIdClass').text();
var tr = $(this).closest('tr');
var row = $('#replyTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
format(row.child, id); // here pass the reply id to function format
tr.addClass('shown');
}
});
function format(callback, vRid) {
var TicketID = $("#txtTicketID").val();
var repId = $(this).text();
$.ajax({
type: "GET",
url: "/api/TicketAttachmentApi/GetRepliesAttachments/" + vRid,
dataType: "json",
cache: false,
complete: function (response) {
var data = JSON.parse(response.responseText);
console.log(data);
var tbody = "";
$.each(data, function (i, d) {
tbody += "<tr><td><a href='/Attachments/Tickets/" + TicketID + "/Replies/"
+ vRid + "/" + d.fileName + "' target='_blank'>" + d.fileName + "</a></td></tr>";
});
console.log("<table>" + tbody + "</table>");
callback($("<table>" + tbody + "</table>")).show();
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
} //-- end format (callback)
});
</script>
I need generate table in success ajax and draw in html. But I dont know how can I fill my table. I try this, but nothing draw.
$.ajax({
url: '/Private/Index',
method: 'POST',
dataType: "json",
data: $(addNewEduForm).serialize() + '&' + $.param(mm),
traditional: true,
success: function (selected) {
$('#your-modal').modal('toggle');
var row = $('<tr>');
for (var i = 0; i < selected.length; i++) {
row.append($('<td>').html(selected[i]));
}
$('#results').append(row);
},
error: function (error) {
}
});
My console.log(selected) :
PICTURE
And my html, where I need draw the table:
<table class="table_blur">
<tr>
<th>Date</th>
<th>Event</th>
<th>First</th>
</tr>
</table>
As result I need :
<th>Date</th><th>Event</th><th>FirstTeam</th>
<DateFromSelected><EventFrom Selected><FirstTeam>
You need that your code looks like that, for example you need show DateofEvent and FirstTeam.
HTML CODE
<table id="results">
<thead>
<tr>
<td>DateofEvent</td>
<td>FirstTeam</td>
</tr>
</thead>
<tboby>
</tbody>
</table>
JS CODE
$.ajax({
url: '/Private/Index',
method: 'POST',
dataType: "json",
data: $(addNewEduForm).serialize() + '&' + $.param(mm),
traditional: true,
success: function (selected) {
$('#your-modal').modal('toggle');
var row = $('<tr>');
for (var i = 0; i < selected.length; i++) {
row.append($('<td>').html(selected[i].DateofEvent));
row.append($('<td>').html(selected[i].FirstTeam));
}
$('#results').append(row);
},
error: function (error) {
}
});
*remember that you return a collection of objects and you access them by name.
I'm updating records in my database using a checkbox in a table. I'm trying to offer 1 Alert after ALL the updates went through, rather than alerting for each individual success call
$('#update').click(function () {
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
alert('updated!');
}
});
Is this possible?
Count your successful calls and compare with the total number of calls.
$('#update').click(function () {
var calls=$('#view_26 tbody input[type=checkbox]:checked').length;
var success=0;
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
success+=1;
if(success==calls) alert('updated!');
}
});
Maybe you should also catch unsuccessful calls.
Can you build and PUT the entire JSON array instead of one row at a time? This, of course, would require modifying your web service to get the record id from the JSON instead of the url. It's a better practice to limit your calls in this manner.
$('#update').click(function () {
var myJSON=[];
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
myJSON.push({ID:id,field_1:'Closed'});
});
//end of each
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/',
type: 'PUT',
data: myJSON,
success: function (response) {
alert('updated!');
}
});
All you need to do is to compare the length of checkboxes against the index to see if they are equal, like below.
$('#update').click(function () {
var checkboxes = $('#view_26 tbody input[type=checkbox]:checked'),
len = checkboxes.length;
checkboxes.each(function(i) {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
if (i === len - 1 ) {
alert('updated!');
}
}
});
})
});
Try
$('#update').click(function () {
var elem = $('#view_26 tbody tr input[type=checkbox]:checked');
var res = $.map(elem, function(el, i) {
var id = $(el).closest('tr').attr('id');
console.log(id);
return $.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'}
});
});
$.when.apply($, res)
.then(function() {
alert("updated!");
}, function(jqxhr, textStatus, errorThrown) {
alert(textStatus +" "+ jqxhr.status +" "+ errorThrown);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update">update</button>
<table id="view_26">
<tbody>
<tr id="0">
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr id="1">
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr id="2">
<td>
<input type="checkbox" value="">
</td>
</tr>
</tbody>
</table>
I have a file data.php, when a user clicks update the database is updated in background with jquery but in response i want to reload the particular table whose data was updated.
my html:
<div id="divContainer">
<table id="tableContainer" cellspacing='0' cellpadding='5' border='0'>
<tr>
<td>No.</td>
<td>Username</td>
<td>Password</td>
<td>Usage Left</td>
<td>%</td>
</tr><!-- Multiple rows with different data (This is head of table) -->
my jquery:
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('<div id="divContainer" />').slideUp('500').empty().load('data.php #tableContainer', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
Everything is working fine the database is getting updated and in success #response is getting loaded with success message but the table is not refreshing.
You already have a div with an id of divContainer but you are creating this element again
$('<div id="divContainer " />').slideUp....
you need
$('#divContainer')
.slideUp('500')
.empty()
.load('data.php #tableContainer', function() {
$(this).slideDown('1000');
});
$('#UpdateAll').click(function () {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function (response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#divContainer').slideUp('1000').load('data.php #tableContainer', function () {
$(this).hide().appendTo('#tableContainer').slideDown('1000');
});
}
});
});