jQuery Ajaxcall crashing all browsers - javascript

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

Related

How to call a thymeleaf modal fragment from a javascript generated link?

I have a javascript function that renders a table from an ajax call.
The row rendering bit is:
function buildTable(id) {
trHTML = null;
$.ajax({
type: "GET",
url: siteroot + "apiURL" + id,
data: {},
dataType: "json",
cache: false,
success: function (data) {
for (i = 0; i < data.length; i++) {
trHTML +=
'<tr>' +
'<td>' + data[i].value +
'<a class="pull-right" href="#" data-toggle="modal" data-target="#edit-modal" > ' +
'<span class="pull-right glyphicon glyphicon-pencil"></span>' +
'</a>' +
'</td>' +
'<td>' + data[i].text + '</td>' +
'<td>' + data[i].description + '</td>' +
'</tr>';
}
$('#resourceTable').append('<tbody>' + trHTML + '</tbody>');
},
error: function (msg) {
alert(msg.responseText);
}
});
}
And the modal is defined as:
<div th:replace="../../modals/modal"></div>
The issue I am facing is that the link is here on the rendered table, but when I click it, the modal does not come on.
What am I not seeing here?

How to set Onclick dynamic to generated rows?

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.

How to get ajax response on a button click

I am getting table data from ajax response as json.Some json datas am not displaying but I want it on a button click for other purpose.How can I get it?Please help me.
function leaveTable() {
for (var i = 0; i < leaveList.length; i++) {
var tab = '<tr id="' + i + '"><td>' + (i + 1) + '</td><td class="appliedOn">' + leaveList[i].appliedOn + '</td><td class="levType" >' + leaveList[i].levType + '</td><td class="leaveOn" >' + leaveList[i].leaveOn + '</td><td class="duration">' + leaveList[i].duration + '</td><td class="status">' + leaveList[i].status + '</td><td class="approvedOn">' + leaveList[i].approvedOn + '</td><td class="approvedBy">' + leaveList[i].approvedBy + '</td><td><i class="btn dltLev fa fa-times" onclick="cancelLeave(this)" data-dismiss="modal" value="Cancelled"></i></td><tr>';
$('#levListTable').append(tab)
}
}
from ajax response I want leaveTypeId and pass it into sendCancelReq() function.
Complete code :https://jsfiddle.net/tytzuckz/18/
It is complicated to know exactly what you want. I hope that helps you:
The first, I would change, is not to produce the JavaScript events in your html code var tab = .... I think, it is more clear and readable, when you add your event after the creation of the new dom elements. For example:
var tab = $('<tr id="' + i + '">' +
'<td>' + (i + 1) + '</td>' +
'<td class="appliedOn">' + leaveList[i].appliedOn + '</td>' +
'<td class="levType" >' + leaveList[i].levType + '</td>' +
'<td class="leaveOn" >' + leaveList[i].leaveOn + '</td>' +
'<td class="duration">' + leaveList[i].duration + '</td>' +
'<td class="status">' + leaveList[i].status + '</td>' +
'<td class="approvedOn">' + leaveList[i].approvedOn + '</td>' +
'<td class="approvedBy">' + leaveList[i].approvedBy + '</td>' +
'<td><i class="btn dltLev fa fa-times" data-dismiss="modal" value="Cancelled"></i></td>' +
'<tr>');
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this); });
Then, you are able to send your necessary information more clearly, e.g.:
Instead of the last code
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this); });
you can write
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this, leaveList[i].leaveTypeId); });
and extend your method cancelLeave to:
function cancelLeave(elem, leaveTypeId) {
var id = $(elem).closest('tr').attr('id')
alert(id)
$("#cancelLeave").modal("show");
$('.sendCancelReq').val(id);
sendCancelReq(leaveTypeId);
}
Got solutionPlease check this:https://jsfiddle.net/tytzuckz/19/
function cancelLeave(elem) {
var levTypeId = $(elem).attr('id')
var id = $(elem).closest('tr').attr('id')
$('.currentLevTypeId').val(levTypeId);
$("#cancelLeave").modal("show");
$('.sendCancelReq').val(id);
}
function sendCancelReq() {
var a= $('.currentLevTypeId').val();
alert(a)
}

Error: Cannot read property 'each' of undefined

I have a JavaScript code that returns values of a PHP and assembles an HTML table. Is giving the error can not read property of each undefined. I've looked several times without success. They could give me a hand?
The following code:
JavaScript:
function getListaItems(idprojeto) {
//alert(idprojeto);
jQuery.ajax({
type: "POST",
url: "get-lista-items.php?idprojeto=" + idprojeto,
//data: dataEvento,
dataType: 'json',
success: function(resposta) {
var str_html = '';
$.each(resposta, function(){
str_html = str_html + '<tr class="gradeA" id="' + this.id + '">' +
'<td class="center"><input type="checkbox" id="item[]" name="item[]" onchange="changeColor(' + this.id + ')" value="' + this.id + '" /></td>' +
'<td class="center">' + this.descricao + '</td>' +
'<td class="center">' + this.descCategoria + '</td>' +
'<td class="center">' + this.descCaracteristica + '</td>' +
'<td class="center">' + this.descMedida + '</td>' +
'<td class="center"><input type="text" id="qtd' + this.id + '" style="width:80px"/></td>' +
'</tr>';
});
document.getElementById("resultJs").innerHTML = str_html;
}
});
}
PHP:
<?php
session_start();
require_once("ProjectIncludes.php");
$service = new ProjetoxItensService();
$consulta = $service->getAll($_GET['idprojeto']);
$retorno = json_encode($consulta);
echo $retorno;
?>
Thanks, guys.
Looks like jQuery is not available using $, try jQuery instead.
Change this line:
$.each(resposta, function(){
to this:
jQuery.each(resposta, function(){

javascript function saying it doesn't exist when it does

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.

Categories