Script disables some components on my table - javascript

This is how my webpage looks like:
As can be seen in the picture I have I have search on the top right, in the bottom right I have the amount of pages etc..
But as I add another project here by clicking "Lägg till ny" and add a project for some reason my page will end up like this:
http://puu.sh/kKSZz/387c71f487.png
As can be seen the table "Breaks" the search field gets removed and so does the pages. Same things happens when I chose to edit or delete a project I've already added.
This is my view:
<div id="tabs-current">
<div id="ConsultantTimes">
#{
Html.RenderAction("ConsulantTimes");
}
</div>
<a href="javascript:OpenDialog()" class="btn btn-primary">
Lägg till ny
</a>
</div>
As can be seen the table is a partial view and here it is:
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>Projekt</th>
<th>Mitt Datum</th>
<th>%</th>
<th>Projektdatum</th>
</tr>
</thead>
<tbody>
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}
</tbody>
And this is my script I run when I choose to add another project:
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 220,
width: 305,
modal: true,
buttons: {
'Spara': function() {
if (!validate()) {
alert('Procent måste vara mellan 0-100');
return false;
}
locstring = "#(Url.Action("Index"))/Update/?";
locstring += '&projectId=' + $('#projectList').val();
locstring += '&startDate=' + $('#startDate').val();
locstring += '&endDate=' + $('#endDate').val();
locstring += '&pct=' + $('#pct').val();
var sid = $('#sId').text();
if (sid != "") {
locstring += '&id=' + sid;
//locstring = "/Delete/" + sid;
}
//window.location = locstring;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
//alert(locstring);
$('#dialog').dialog('close');
ReloadTable();
}
});
},
'Avbryt': function() {
$(this).dialog('close');
},
'Ta bort': function() {
var sid = $('#sId').text();
if (sid != "") {
locstring = "#(Url.Action("Index"))/Delete/" + sid;
//locstring += '&delete=true&id=' + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
ReloadTable();
}
});
Note, when this happends I have no errors in my console.
Found the error but not sure how to solve it, it's my ReloadTable function:
function ReloadTable() {
if (navigator.appName == "Microsoft Internet Explorer") {
//alert('suck..');
window.location.reload();
} else {
$.ajax({
type: "GET",
url: '#(Url.Action("ConsulantTimes"))',
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
$('#ConsultantTimes').html(data);
}
});
}
}

What you are doing is replacing the entire contents of #ConsultantTimes and replacing it with the data variable. Use $( "sample_1" ).replaceWith(data); instead, or maybe prepend or append.

Related

How can I debug AngularJS function not getting called?

I have a table
I have constructed these rows and action buttons dynamically as soon as user clicked on Devices accordion.
When the user clicks on the (I)
<i class="fa fa-info ml15"></i>
It should called expandCollapseCurrent() function. Somehow it never reaches there, and there is nothing in the console for me to understand why it didn’t reach
$scope.expandCollapseCurrent = function(currentDevice) {
console.log('%c currentDevice = ' + currentDevice, "color: green;");
angular.forEach($scope.private_devices, function(device) {
if(device.name != currentDevice.name) {
device.settingsEnabled = false;
device.viewEnabled = false;
}
$scope.buttonShow.bandwidth = false;
$scope.buttonShow.acl = false;
});
}
It never did.
This is my entire code for that.
$('#wifi-devices-nav').click( function() {
if($('#wifi-devices-nav').hasClass('callout-expanded')) {
$.ajax({
method: 'GET',
url: '/api/telenet/' + '{{ $cpe_mac }}' + '/privateDevices',
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
success: function(response){
$('.lds-ripple').fadeOut();
console.log(response.length);
for (i = 0; i < response.length; i++) {
var device = response[i];
if(device.up) {
console.log(device);
}
if(device.device_activity != "OFFLINE" && device.device_activity_v6 != "OFFLINE" ) {
console.log(response[i]);
if(device.up) {
var uplink = device.up.value + ' ' + device.up.suffix;
}
if(device.down) {
var downlink = device.down.value + ' ' + device.up.suffix;
}
if(device.device_activity == 'ACTIVE') {
var deviceStatus = 'green';
}else {
var deviceStatus = 'orange';
}
let row = `
<tr id="tr-${device.device_mac}">
<td>
{{-- Status --}}
<i class="device-status-circle fa fa-circle ${deviceStatus}" style="margin-left:7px; ">
</i>
${device.device_mac}
</td>
<td class="text-center">${device.ip_address_v6}</td>
<td class="text-center">${device.last_active} </td>
<td class="text-center">
<!-- View -->
<i class="fa fa-info ml15"></i>
<!-- Edit -->
<i class="fa fa-pencil ml15"></i>
<!-- Settings -->
<i class="fa fa-cog ml15"></i>
</td>
</tr>
`;
$('#tablePrivateDevices').prepend(row).fadeIn('slow');
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
});
Updated Observations
Any of the 3 buttons that I clicked, will refresh the page.
I have NO idea why it does that ...
Any hints/suggestions will mean a lot to me.
You can not just add html like <button ng-click="... you need to $compile it first. As you do not, directive is ignored and you get default browser behaviour - it follows href.
P.S. This mixture of jquery and angularjs looks pretty akward...

Get data in child row based on id on parent row, using two ajax calls in datatable - jQuery

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>

Display table on button click using ajax

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

Asp.net / JavaScript Can't remove entry from table

I'm trying to remove my entry to my table but when I press the remove button nothing happends, I know it goes into the remove method as it hits my Alert I did set there.
This is my Script to open a dialog:
function OpenDialog2(id, projectId, startDate, endDate, pct) {
ClearDialog();
$('#projectList').val(projectId);
$('#startDate').val(startDate);
$('#endDate').val(endDate);
$('#pct').val(pct);
$('#sId').text(id);
$('#dialog').dialog('open');
}
This is my method trying to remove it:
'Ta bort': function () {
alert("Ta bort");
var sid = $('#sId').text();
if (sid !== "") {
locstring = "#Url.Action("Index")/Delete/" + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function (data) {
$('#dialog').dialog('close');
reloadTable();
}
});
}
This is my Partial View:
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}

Trigger the controller to display view

I have a dropdown in view that is using js I pass the selected item from dropdown to controller, inside the controller I ran a query using the selected item from dropdown to extract some records. Now the problem is that I cannot display the query result to view. Basically I cannot trigger the controller to display in view. Any help greatly appreciated.
Here is the js to pass the data to controller:
<script type="text/JavaScript">
$(function(){
$('.defined_call').bind('change', function(){
alert($(this).val());
$.ajax({
url: "<%= changeowner_path %>",
data: { my_str: $(this).val() }
});
});
});
</script>
<%= select_tag "dropdown_cases", options_for_select(#ownerlist),{:id=>"defined_Id",:class
=> "defined_call'} %>
Here is the controller:
class ReassignsController < ApplicationController
def changeowner
i=0
$myarr=[]
ownerl = Transaction.owner#declaredin model
#ownerlist=ownerl.collect { |c| [ c, c ] }#make it for dropdown
value=params[:my_str]#return value from dropdown
$value1=value.to_s#make it for owner table
#owner_records=Transaction.where(:owner => $value1)
===> I would like to display to the view?
end
end
Here is the view that I am using:
<table class="table table-condensed" id="sortTableExample">
<tr>
<th style="text-align:center">Book Name</th>
<th style="text-align:center">Owner</th>
</tr>
<% #owner_records.each do |arr_data| %>
<tr>
<td style="text-align:center"><%= arr_data.book%></td>
<td style="text-align:center"><%= arr_data.owner%></td>
</tr>
<% end %>
</table>
Joe, Try something like:
$('.defined_call').change(function() {
$.ajax({
url: "<%= changeowner_path %>", type: 'get',
data: { my_str: $(this).val() },
dataType: 'json',
processData: false,
success: function(data) {
if (data == "") {
alert('No Results');
}
else {
var jsonObj = eval( data );
var count = jsonObj.transactions.length;
for (var i = 0; i<count; i=i+1) {
$('#sortTableExample').append('<td style="text-align:center">' + jsonObj.transactions[i].book + '</td><td style="text-align:center">' + jsonObj.transactions[i].owner + '</td>');
}
}
}
});
});
Rails is rendering your view, you just aren't doing anything with it on the client side (in javascript).
In your ajax call you want to do something on success:
$.ajax({
url: "<%= changeowner_path %>",
data: { my_str: $(this).val() },
success: function(data) {
$('#myDiv').html(data); // This is writing the returned view from rails to myDiv
}
});

Categories