I'm trying to call a JavaScript function and then pass the value of the button clicked to that function but even though the function does exist its saying it doesn't and im not sure why. Basically I need to call the powerOn() function when the power on button is clicked and then return the status messages. All I need to know is why it won't call the function so I can make sure I get the basic response.
Also I'm not entirely sure why sortable returns a console error when im following the documentation on http://github.hubspot.com/sortable/api/options/:
ReferenceError: Sortable is not defined vmstatus:123
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5375
TypeError: powerOn is not a function
Code:
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#table-repeat-data').remove();
setInterval(update, 1000);
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
$('#table_name').append("<table class='table' id='table-repeat-data' data-sortable><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + on + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}else{
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + off + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
function update(){
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = on;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}else{
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = off;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}
}
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
function powerOn() {
console.log('powerOn');
console.log(this.val());
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_vm : $(this).val(),
username : '{{user_name}}',
ip_address: '{{ip}}',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
console.log(json.server_response);
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
Sortable.init();
var dataTable;
dataTable = document.querySelector('#table-repeat-data');
Sortable.initTable(dataTable);
</script>
Try changing the name of your function, or changing the name of your variable of the same name. It's possible that it is getting confused as to which one you actually mean due to scope.
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
function powerOn() {...}
which one is powerOn? They both are. It's possible that your function is later overridden to a string value and then it is no longer valid to try and call it like it was a function.
Related
I have experience with PHP and HTML, but I am unfamiliar with JS. I have all the code needed, but I can't put it together. I have a table and need to add a delete button that will remove the file on that row. As shown in the picture below, but without the edit button:
When click on the Search button, the table is displayed (here is where I need the delete button):
index.php
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;'/>
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px; display:none">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
main.js
function Search(){
var crop = $("#crop").val();
var type = $("#type").val();
var year = $("#year").val();
var season = $("#season").val();
var location = $("#location").val();
var subLocation = $("#sublocation").val();
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
$.ajax({
url: "Resources/PHP/Search.php",
dataType: 'text',
data: {
crop: crop,
type: type,
year: year,
location: location,
season: season,
sublocation: subLocation
},
success: function(response) {
var data = JSON.parse(response);
var items = "";
var firstSet = 0;
if (data.length > 0)
{
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
$("#imported-set-wrapper").html(table);
$.each(data,function(index,item)
{
if (index == 0){
firstSet = item.ID;
}
items+= "<tr id='data-set-" + item.ID + "' onclick='SelectDataSet(\"" + item.ID + "\"); return false;' style='cursor:pointer'>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
var rowHeight = 61;
var padding = 10;
var actualHeight = (data.length + 1) * rowHeight + padding;
var maxHeight = 300;
var height = actualHeight < maxHeight ? actualHeight : maxHeight;
$('#imported-set-table').fxdHdrCol({
fixedCols: 0,
width: 1100,
height: height,
colModal: [
//added
{ width: 150, align: 'center' },
//added
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 250, align: 'center' },
{ width: 175, align: 'center' },
{ width: 150, align: 'center' },
],
sort: false
});
if (firstSet > 0){
$("#next").prop("disabled", false);
SelectDataSet(firstSet);
$("#data-set-fs").show();
} else {
alert("No dataset found");
}
}
$("#processing").hide();
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
$("#processing").hide();
}
});
}
Useful code from picture 1
"<input id='delete-" + type + "-" + item.ID +"' type='image' class='image-button delete-button' src='Resources/Images/delete.png' alt='Delete' onclick='Delete(" + item.ID +", \"" + type + "\"); return false;' title='Delete'>" +
"<input id='confirmDelete-" + type + "-" + item.ID +"' type='image' class='image-button confirm-delete-button' src='Resources/Images/confirm.png' alt='Confirm' style='display:none' onclick='ConfirmDelete(" + item.ID +", \"" + type + "\"); return false;' title='Confirm'>" +
"<input id='cancelDelete-" + type + "-" + item.ID +"' type='image' class='image-button cancel-delete-button' src='Resources/Images/cancel.png' alt='Cancel' style='display:none' onclick='CancelDelete(" + item.ID +", \"" + type + "\"); return false;' title='Cancel'>" +
function Delete(id, type){
$('#confirmDelete-' + type + '-' + id).show();
$('#cancelDelete-' + type + '-' + id).show();
$('#delete-' + type + '-' + id).hide();
CancelEdit(id);
}
function CancelDelete(id, type){
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
}
function ConfirmDelete(id, type){
$.ajax({
url: 'Resources/PHP/' + type + '.php',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
alert("The " + type + " has been deleted.");
GetList(type);
} else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});
}
Additional info: "//added" are additional lines trying to achieve mentioned goal.
You can add your button like this "<button data-id = " + item.ID + " class='delete'>Delete</button>" where data-id has your item.ID value this will get passed to your backend to perform delete operation.
Then , when delete button get clicked this $(document).on("click", ".delete",.. will get called you can show confirm-box so if user click ok then call your ajax to delete that trs data using selector.closest('tr').remove() where selector refer to the button which has been clicked .
Demo Code :
//dummy datas
var data = [{
"Year": "2016",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "1"
}, {
"Year": "2017",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "2"
}]
function Search() {
//some codes..
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
//other codes...
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
var items = "";
$("#imported-set-wrapper").html(table);
$.each(data, function(index, item) {
if (index == 0) {
firstSet = item.ID;
}
items += "<tr id='data-set-" + item.ID + "' onclick='' style='cursor:pointer'>" +
"<td style='overflow:hidden'>" +
//added button with data-* attribute
"<button data-id = " + item.ID + " class='delete'>Delete</button>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
//soem ot//other codes..
}
//onclick of delete button
$(document).on("click", ".delete", function() {
var id = $(this).data('id'); //get id
var selector = $(this);
console.log(id)
//show confirm box if yes
if (confirm("Are you sure?")) {
//ajax call
/*$.ajax({
url: 'url',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {*/
selector.closest('tr').remove() //remove tr
/* } else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});*/
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;' />
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px;">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
Where you have:
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
Doesn't this need to be the button? E.g.
<td><button onclick='deleteFunction(item.id)'>Delete</button></td>
I'm trying to build search filter with .keyup function. When i write one char in search textbox its works fine, but when i try to delete char, or add one more then it crushes and throws error "Internal server error". What im i doing wrong? I tried to parse given/taken data to json/html and it didn't help. Here is my script code:
<script>
$(document).ready(function () {
$("#Search").keyup(function () {
var searchby = $("#searchby").val();
var searchVal = $("#Search").val();
var setData = $("#dataSearching");
var catId = $("#categoryID").val();
setData.html("");
$.ajax({
async: true,
type: "get",
url: "/Default/GetSearchingData?categoryID=" + catId + "&searchBy=" + searchby + "&searchValue=" + searchVal,
dataType: "json",
contentType: "html",
success: function (result) {
if (result.length == 0) {
setData.append('<tr><td colspan="7" style="color: red;">Nie odnaleziono szukanej frazy</td></tr>');
} else {
for (var i in result) {
var Data = "<tr>" +
"<td>" + result[i].AlbumID + "</td>" +
"<td>" + result[i].AlbumName + "</td>" +
"<td>" + result[i].BandName + "</td>" +
"<td>" + result[i].AlbumCover + "</td>" +
"<td>" + result[i].Year + "</td>" +
"<td>" + parseFloat(result[i].Price) + "</td>" +
"<td>" +
"<button id=" + result[i].AlbumID + ' type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-' + result[i].AlbumID + '">' +
"Zobacz </button>" +
'<div class="modal fade" id="exampleModal-' + result[i].AlbumID + '" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-' + result[i].AlbumID + '" aria-hidden="true">' +
'<div class="modal-dialog" role="document">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<h5 class="modal-title" id="exampleModalLabel-' + result[i].AlbumID + '">' + result[i].AlbumName + ", " + result[i].Year + ", " + result[i].BandName + "</h5>" +
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">×</span> </button> </div>' +
'<div id="parent-' + result[i].AlbumID + '" class="modal-body">' +
"</div>" +
'<div class="modal-footer">' +
'<button id="closeModal" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</td>" +
"<td>"+
'<input id="categoryID" class="hidden" type="submit" value="' + result[i].CategoryID + "/>" +
"</td>"+
"</tr>";
setData.append(Data);
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.responseText);
alert("Error!!: " + thrownError);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
return xhr;
}
});
});
});
</script>
And here is my action for searching in DefaultController:
public JsonResult GetSearchingData(int categoryID, string searchBy, string searchValue)
{
var albumsWithCategory = (from album in Album.GetAlbumList()
join category in Category.GetCategoriesList()
on album.CategoryID equals category.CategoryID
where (categoryID == album.CategoryID)
select album).ToList();
List<Album> newAlbumList;
if (searchBy == "AlbumName")
{
newAlbumList = albumsWithCategory.Where(x => x.AlbumName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
else
{
newAlbumList = albumsWithCategory.Where(x => x.BandName.StartsWith(searchValue, StringComparison.InvariantCultureIgnoreCase) || searchValue == null).ToList();
return Json(newAlbumList, JsonRequestBehavior.AllowGet);
}
}
Here is my data model (if it would be useful to find issue):
public class BigViewModel
{
public IEnumerable<Album> Albums { get; set; }
public IEnumerable<Category> Categories { get; set; }
public IEnumerable<Order> Orders { get; set; }
public IEnumerable<Song> Songs { get; set; }
}
Image with error:
enter image description here
I believe that error is due formatting in query parameters. Instead of keyup i would try to use input event and instead of building query url i would use data property.
$("#Search").on("input", function () {
//...
$.ajax({
url: "/Default/GetSearchingData",
type: "get",
dataType: "json",
data: {
categoryID: Number(catId),
searchBy: searchBy,
searchValue: searchVal
},
success: function(result) {
if (result.length > 0)
{
var rows = response.map(item => {
return `
<tr>
<td>${item.AlbumID}</td>
<td>${item.AlbumName}</td>
<td>${item.BandName}</td>
<td>${item.AlbumCover}</td>
<td>...</td>
</tr>
`;
}).join("");
setData.html( `<table>${rows}</table>` );
} else {
setData.html( "<table><tr>Not found</tr></table>" );
}
},
error: function(xhr) { }
});
});
function GetPage(pageIndex) {
debugger;
$.ajax({
cache: false,
//url: "/EmailScheduler/",
url: '#(Url.RouteUrl("EmailScheduler"))',
type: "POST",
data: { "selectValue": pageIndex },
traditional: true,
dataType: "json",
success: function (data) {
debugger;
$('#GridRows').empty();
$('#pager').empty();
var trHTML = '';
var htmlPager = '';
$.each(data.Customers, function (i, item) {
trHTML += '<table class="table-bordered col-offset-12"><tr style="text-align:center">'
+'<td id="tblFirstName"> ' + item.FirstName + '</td>'
+'<td id="tblLastName"> ' + item.LastName + '</td>'
+'<td id="tblEmailID"> ' + item.EmailID + '</td>'
+'<td id="tblCustomerType"> ' + item.CustomerType + '</td>'
+'<td id="tblCustomerDesignation"> ' + item.CustomerDesignation + '</td>'
+' <td><div class="checkbox control-group"><label><input type="checkbox" id="item.CustomerID" value="item.CustomerID" onclick="AddRemoveCustomer(item.CustomerID)" class="checkBoxClass"/></label></div></td></tr></table>'
});
$('#GridRows').append(trHTML);
if (data.Pager.EndPage > 1) {
htmlPager += '<ul class="pagination">'
if (data.Pager.CurrentPage > 1) {
htmlPager += '<li><input class="myButton" style="width:25px;height:25px;" type="button" id="1" style="font-weight:bold;" value="<<" /></li><li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage - 1) + '"value="<"></li>'
}
for (var page = data.Pager.StartPage; page <= data.Pager.EndPage; page++) {
htmlPager += '<li class="' + (page == data.Pager.CurrentPage ? "active" : "") + '"><input type="button" class="myButton" id="' + page + '" value="' + page + '"/></li>'
}
if (data.Pager.CurrentPage < data.Pager.TotalPages) {
htmlPager += '<li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage + 1) + '" value=">"/></li><li><input type="button" class="myButton" id="' + (data.Pager.TotalPages) + '" value=">>"/></li>'
}
htmlPager += '</ul>'
}
$('#pager').append(htmlPager);
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}
**
Scenario:-
**
In this ajax table rows generated.
How to call onClick function for checkbox in Ajax generated rows?
I want to call onClick function in which checked id's stored in hidden
field.
what should i do?
try to update :
+' <td><div class="checkbox control-group"><label><input
type="checkbox" id="'+item.CustomerID+'"
value="'+item.CustomerID+'" class="checkBoxClass"/>
</label></div></td></tr></table>'
and add this :
$(document).on('click', '#GridRows .checkBoxClass' ,
function(){
alert('hello');//todo something....
});
Try to do something like this
function delegateAction(){
$('.checkBoxClass').click(function(event){
// do some action
});
}
delegateAction();
After ajax load you can call "delegateAction()", and the event click will be activated.
I'm doing a async ajax django post that returns a list of vms with properties. I can't seem to get the HTML format to format correctly. It doesn't draw the tables with the styles, it just outputs the text, and I can't see the output because the debugger either didn't receive it or its hiding it.
this is what my console output looks like
<div id="table_name"></div>
</tbody>
</table>
</div>
Here is my Javascript:
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
console.log('Good');
for (index = 0; index < json.vmlist.length; ++index) {
if(index < 0){
document.getElementById('table_name').innerHTML = "<table class='sortable table' id='table-data'><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>";
}else{
document.getElementById('table_name').innerHTML = document.getElementById('table_name').innerHTML +'<tr><td>'+ json.vmlist[index][0] + '</td><td>' +json.vmlist[index][1] + '</td><td>' +json.vmlist[index][2] + '</td></tr>';
}
}
console.log( 'Server Response: ' + json.server_response + json.vmlist);
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
sorry for the long text I didn't know if I could put it in () and make it multi line.
Thanks to Tom I was able to get it working, but I have to make one last tweak, I'm writing an if statement to draw an image in place of index[1] for on or off. However it just always draws the on. The three possible values are poweredOn poweredOff or suspended I need to draw an image for all three states.
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
console.log('Good');
$('#table_name').append("<table class='sortable table' id='table-repeat-data'><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
if(json.vmlist[index][1] = 'poweredOn'){
$('#table-repeat-data').append ('<tr><td>' + json.vmlist[index][0] + '</td><td>' + on + '</td><td>' + json.vmlist[index][2] + '</td></tr>');
}else{
$('#table-repeat-data').append ('<tr><td>' + json.vmlist[index][0] + '</td><td>' + off + '</td><td>' + json.vmlist[index][2] + '</td></tr>');
}
}
So all I have yet to figure out is how to get the sorter to work.
http://www.kryogenix.org/code/browser/sorttable/ is the sorter I used.
Also,
I dynamically update the information. I dynamically assign vmlist[2] position which is a vmid to that dynamic id to the tds, i want to empty the tds and refill as it loops through the information. Here is my code but the problem is the console out puts the following:
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5375
"Good" vmstatus:40
"update!" vmstatus:51
this is when it calls the first update:
TypeError: document.getElementById(...).empty is not a function vmstatus:85
"Good" vmstatus:73
120
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
setInterval(update, 5000);
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
console.log('Good');
$('#table_name').append("<table class='sortable table' id='table-repeat-data'><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
if(json.vmlist[index][1] == 'poweredOn'){
$('#table-repeat-data').append ('<tr><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][0] + '</td><td id=' + json.vmlist[index][2] + '>' + on + '</td><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][2] + '</td></tr>');
}else{
$('#table-repeat-data').append ('<tr><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][0] + '</td><td id=' + json.vmlist[index][2] + '>' + off + '</td><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][2] + '</td></tr>');
}
}
console.log( 'update!');
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
function update(){
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
console.log('Good');
for (var index = 0; index < json.vmlist.length; index++) {
if(json.vmlist[index][1] == 'poweredOn'){
document.getElementById(json.vmlist[index][2]).empty();
$('#table-repeat-data').append ('<tr><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][0] + '</td><td id=' + json.vmlist[index][2] + '>' + on + '</td><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][2] + '</td></tr>');
}else{
document.getElementById(json.vmlist[index][2]).empty();
$('#table-repeat-data').append ('<tr><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][0] + '</td><td id=' + json.vmlist[index][2] + '>' + off + '</td><td id=' + json.vmlist[index][2] + '>' + json.vmlist[index][2] + '</td></tr>');
}
}
console.log( 'update!');
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
</script>
There are a number of issues with your code, try this instead:
function isPowered(string) {
var onImg = '<img src="http://placekitten.com/g/200/300"/>';
var offImg = '<img src="http://placehold.it/100x100"/>';
return (string == 'poweredOn') ? onImg : offImg;
}
$(document).ready(function () {
$('#table_name').append("<table class='sortable table' id='table-data' data-sortable><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
$('#table-data').append ('<tr><td>' + json.vmlist[index][0] + '</td><td>' + isPowered(json.vmlist[index][1]) + '</td><td>' + json.vmlist[index][2] + '</td></tr>');
}
Sortable.init();
});
Fiddle
ALSO: You will want to re-initialize any javascript AFTER the table is built for things like tooltips and sortable, etc.
I have a (heavy) function that fetches some data from php/sql and then render it in html. When I load the page for the first time I call this function and everything is fine. When I click on a button I call this function also after an successfull other ajax call, but then my browsers freezes and crashes. I get in Firefox and Chrome an error (page unresponsive).
Here the (heavy)function:
function getMinerAttributesByType(type) {
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
timeout : 8000,
data : {getMinerAttributesByType:type}
}).success(function(json){
$tableConfigured = $("#keywordsgroupsConf tbody");
$tableConfigured.html("");
$tableUnconfigured = $("#keywordsgroups tbody");
$tableUnconfigured.html("");
$.each(json, function(key, value){
var $table;
if (value.configured == 0) {
$table = $tableUnconfigured;
} else {
$table = $tableConfigured;
}
$table.append('<tr>' +
'<td>' + value.name + '</td>' +
'<td><button class="btn btn-info" data-toggle="collapse" data-target="#'+ value.id+'-subs" data-id="'+ value.id +'" data-init="0">Config</button></td>' +
'</tr>' +
'<tr class="dataset">' +
'<td colspan="2" class="subrow">' +
'<div style="background:#eee;" class="accordian-body collapse" id="'+ value.id+'-subs">' +
'<table style="margin-bottom: 10px;" class="table" id="table-' + value.id + '" data-id="' + value.id + '">'+
'<tbody>' +
'</tbody>' +
'</table>'+
'<div style="margin-left:10px;" class="input-append">'+
'<input type="text" placeholder="Keywordgroup name">'+
'<button class="btn btn-create-keywordgroup" data-id="' + value.id + '"><i class="icon icon-plus"></i> Add</button>'+
'<button class="btn btn-success btn-mark-as-c" data-id="' + value.id + '"><i class="icon-white icon-check"></i> Mark as configured</button>' +
'</div>' +
'</div>' +
'</td>'+
'</tr>');
});
});
}
Here the function that call the function and crashes afterwards:
$(document).on("click", ".btn-mark-as-c", function(){
if (confirm("Are you sure you want to mark this attribute as configured?")) {
$this = $(this)
var id = $this.attr("data-id");
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
data : {updateMinerAttributeState:id, state:1}
}).success(function(json){
if (json.status == "success") {
// crashes here in this call of the heavy function
getMinerAttributesByType(1);
} else {
alert("There was an error!");
}
});
}
});
Someone a pointer?
I dont have 50 rep so I cant comment yet buuuut, couldn't you bust out that chunk of HTML formatting to a PHP document, and then use the AJAX to call the PHP and return the result? Then use $table.append(result)?
Ex)
<script type="text/javascript">
jQuery(document).on('click', '.menuItem', function()
{
event.preventDefault();
var mainCategory = $(this).attr('id').split('xx')[0];
$.ajax({
url: '/php/SubMenuBar.php', <----- Access the PHP file.
data: {
MainCategory: mainCategory, <---- Parameters for the PHP file (declared using $_GET() in the PHP file)
},
success: function(result) <--- Result becomes the output from the PHP file
{
$table.append(result);
}
});
Instead of appending the rows to the DOM one at a time, concatenate them into a string and then add them all at once.
function getMinerAttributesByType(type) {
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
timeout : 8000,
data : {getMinerAttributesByType:type}
}).success(function(json){
var $tableConfigured = $("#keywordsgroupsConf tbody");
var $tableUnconfigured = $("#keywordsgroups tbody");
var rowsConfigured = '', rowsUnconfigured = '';
$.each(json, function(key, value){
var row = '<tr>' +
'<td>' + value.name + '</td>' +
'<td><button class="btn btn-info" data-toggle="collapse" data-target="#'+ value.id+'-subs" data-id="'+ value.id +'" data-init="0">Config</button></td>' +
'</tr>' +
'<tr class="dataset">' +
'<td colspan="2" class="subrow">' +
'<div style="background:#eee;" class="accordian-body collapse" id="'+ value.id+'-subs">' +
'<table style="margin-bottom: 10px;" class="table" id="table-' + value.id + '" data-id="' + value.id + '">'+
'<tbody>' +
'</tbody>' +
'</table>'+
'<div style="margin-left:10px;" class="input-append">'+
'<input type="text" placeholder="Keywordgroup name">'+
'<button class="btn btn-create-keywordgroup" data-id="' + value.id + '"><i class="icon icon-plus"></i> Add</button>'+
'<button class="btn btn-success btn-mark-as-c" data-id="' + value.id + '"><i class="icon-white icon-check"></i> Mark as configured</button>' +
'</div>' +
'</div>' +
'</td>'+
'</tr>';
if (value.configured == 0) {
rowsUnconfigured += row;
} else {
rowsConfigured += row;
}
});
$tableConfigured.html(rowsConfigured);
$tableUnconfigured.html(rowsUnconfigured);
});
}