Drag and drop not working on dynamic data - javascript

I am using redips plugin(http://www.redips.net/javascript/drag-and-drop-table-content/) for drag and drop. It is working on static data, but when data comes dynamic through java, the drag and drop stops. I am using the following functions to pick up data on drag and drop:
droppedBefore: function() {}
, finish: function() {}
The plugin is written on pure javascript, so jquery is not working otherwise we could use $(document).live for picking dynamic data
Please suggest something so that drag and drop can work on dynamic data also

Whenever table layout inside drag container is changed, then is needed to call init() or initTables() method. Please see example0 where new table is dynamically appended with jQuery.
http://www.redips.net/my/preview/REDIPS_drag/example00/index2.html
... and here is JavaScript code used in script.js file:
// new table using AJAX/jQuery to the drag container
redips.load_table = function (button) {
// parameter (example for ajax request)
var id = 1;
// disable button (it can be clicked only once)
button.style.backgroundColor = '#c0c0c0';
button.disabled = true;
// AJAX request
$.ajax({
type: 'get',
url: 'ajax.php',
data: 'id=' + id,
cache: false,
success: function (result) {
// load new table
$('#load_content').html(result);
// rescan tables
REDIPS.drag.initTables();
}
});
};

after post request change in table then call
REDIPS.drag.init();
$.ajax({
type: "post",
url: "/recipe/sliderData",
dataType: "json",
data: dataForSlider,
success: function (data) {
//table change
REDIPS.drag.init();//
},
error: function (data) {
alert("Error")
}
});

Related

JS - memory leak - append table

At our MVC project we have this specific View (HTML/JS) where the user can manipulate a large table: select a line and make some operations including move up/down. With move up/down we are facing memory leak: page starts with ~100 MB and goes up until browser crashes (~8 GB at localhost).
Table data is generated at backend, being sent via JSON to frontend. Each line is treated via JS as below:
function LoadTableClient(selectedLine) {
$('#table-client tbody').find('tr').remove(); //Added for clarification
var listClientInformationJson= $('#generalData').data('listclientinformation');
var html = '';
$.each(JSON.parse(listClientInformationJson), function (index, item) {
html += WriteTableClient(item, index, selectedLine);
});
$('#table-client').find('tbody').append(html);
}
When user move up/down it can affect several rows since each line can also be a group containing several rows inside (and other subgroups and so on). Also, we have subtotal and total columns, therefore we need to redraw the hole table.
For this move up/down operation we are triggering a JS function that requests backend via AJAX, and then it gather the response to redraw our table.
$.ajax({
url: '...../MoveTableClientItem',
type: "POST",
contentType: "application/json",
data: JSON.stringify({
...
}),
success: function (response) {
if (response.success) {
GetProjectInfo(); //gets JSON
LoadTableClient(var1); //read JSON and append to table
}
Update: GetProjectInfo function
function GetProjectInfo() {
$.ajax({
url: '..../GetProjectInfo',
type: "POST",
contentType: "application/json",
async: false,
data: JSON.stringify({
...
}),
success: function (response) {
$('#generalData').data('listclientinformation', '');
$('#generalData').data('listclientinformation', response.listClientInformationJson);
},
error: function (response) {
...
}
});
}
It works fine regarding the visual and functional output, the problem is the memory leak. With Chrome "Memory Inspector" we understood that each operation adds ~30 MB to memory due to rows kept in memory.
Update: see attached print showing JS memory increase.
We tried Location.reload() but it was not a good user experience since the hole page is reloaded and what the user was doing is lost (open modals, screen position, etc.)
We tried $("#table-client").empty(); at "response.success" but it just didn't work (nothing changed).
Any ideas on how to solve this?
The issue was related to saving the AJAX response at an element thus making GC (garbage collector) not effective. I managed it by creating a global variable that contains the AJAX response, see below. Now the RAM usage is decreased by GC.
let listClientInformationJson = ''; //Global variable
$(document).ready(function () {
...
//Gets new data with the function below
...
}
function GetProjectInfo() {
$.ajax({
url: '..../GetProjectInfo',
type: "POST",
contentType: "application/json",
data: JSON.stringify({
...
}),
success: function (response) {
listClientInformationJson = undefined; //forces erase
listClientInformationJson = JSON.parse(response.listClientInformationJson);
},
error: function (response) {
...
}
});
}

Reset application STATE after JQUERY AJAX Function

Is there any way to reset an application STATE after every invoking of JQuery Ajax function?
I am developing a small app: users click on a button to invoke a function. But afterwards, when users want to click other buttons to invoke the same function, the dynamic ID of the first clicked button still persisting, so other buttons cannot be addressed anymore.
Code:
$('#submitComment').on('click', function(){
var id = $(this).data('id');
var thiselement = $(this);
$.ajax({
url: 'includes/updateicon.php',
type: 'POST',
data: {id:id},
dataType: 'html',
success: function(data){
if (data) {
$('#submitComment').attr("disabled", true);
$('#customComment').val("");
$('#updatedicon-'+id).html("DONE").removeClass('badge-danger').addClass('badge badge-success');
# CODE HERE TO RESET THE STATE OF THE APP
}
else {
$('#customContent').load("custom/static/error.html");
}
},
error: function(jqXHR, textStatus, errorThrown){
$('#customContent').html("There was an Error about getting the Content:" + errorThrown);
}
});
});
You are searching for elements based on ID and IDs need to be unique (this is most likely causing your bug).
A simple fix of this would be:
$('.submitComment').on('click', function(){
var id=$(this).attr('id');
$.ajax({data:{id:id}});
})

Fullcalendar updateEvent doesn't rerender

I want to add events to my DB via fullcalendar. So I want to add an event and set its id to the id it gets in my DB.
function addCalEvent(event) {
var jEvent = {};
jEvent['startTime'] = moment(event.start).unix();
jEvent['worker']="GUZ"
jEvent['title']=event.title;
if (event.end) {
jEvent['endTime'] = moment(event.end).unix();
}
$.ajax({
url: 'dux.html',
type: 'POST',
data: {
type: 'addNewEvents',
event: jEvent,
REQUEST_TOKEN: "REQUEST_TOKEN>",
},
datatype: 'json',
success: function(data) {
event.id=data;
event.title="NEW";
$('#calendar').fullCalendar('updateEvent', event);
},
});
}
The ajax retrieves the id of the added event and the id and title do get changed, but the 'updateEvent' method doesn't seem to be called, because there is no change to the rendered events title or id.
Ok,
apperently if you make a asynchronous ajax call the order in which commands are executed isn't the order you write it.
I need to add async: false to make this work.
You can manually call rerender events with $('#calendar').fullCalendar( ‘rerenderEvents’ )
Link to docs here

Trouble with jquery ajax and datatables

I am trying to use jquery ajax to get data from a php file. This php file prints a table made from a db query. Once the table is returned to the html page, I wanted to apply datatables styling to the table, but this will not work.
It maybe that I should just use datatables ajax functionality, instead of jquery ajax. I just have three links that a user can click on to call ajax, where not all the links return a printed table.
I suspect it it because of javascript timing, where all the js loads before the table has been output.
I tried using jquery.on(), but could not get it to work with datatables.
I appreciate any help. Sorry if this is confusing.
<script type="text/javascript">
$(document).ready(function() {
// EVENT LISTENER FOR CLICKS
var option_action = "fridge";
var using = "pantry";
$.post("./backend.php", { option: option_action, action: using }, function(data) {
$("#content").html(data);
load_table();
});
// EVENT LISTENER FOR CLICKS
$(".pantry_menu li").click(function() {
alert("CLICK");
//getting data from the html
var option_action = $( this ).attr("name");
var using = "pantry";
$.post("./backend.php", { option: option_action, action: using }, function(data) {
$("#content").html(data);
});
return false;
});
//Mouse action listeners for side bar
$(".pantry_menu li").mouseover(function() {
$(this).css("border-bottom" , "2px solid black");
});
$(".pantry_menu li").mouseout(function() {
$(this).css("border-bottom" , "2px dotted black");
});
$(".fridge_table1").change(function(){
alert("CHANGE");
});
});
function load_table()
{
$('.fridge_table1').dataTable( {
"aaSorting": [[ 4, "desc" ]]
,"bJQueryUI": true
});
}
</script>
In your ajax success function, you can reapply dataTable to the table. For example:
$.ajax({
type: "POST",
url: "ajax.php",
data: {
request: 'something'
},
async: false,
success: function(output)
{
$('#myTableDiv').html(output); //the table is put on screen
$('#myTable').dataTable();
}
});
EDIT due to your update
You need to change the "EVENT LISTENER FOR CLICKS" to call your function that applies dataTables. Change:
$.post("./backend.php", { option: option_action, action: using }, function(data) {
$("#content").html(data);
});
to
$.post("./backend.php", { option: option_action, action: using }, function(data) {
$("#content").html(data);
load_table();
});
You should put the .dataTables() part in the callback of your ajax function
$.ajax{
url: yoururl,
...
success: function(data){
//append the table to the DOm
$('#result').html(data.table)
//call datatables on the new table
$('#newtable').dataTables()
}
otherwise you are trying to transforma table that doesn't exist yet in the DOM

jQuery plugin bsmSelect doesn't update its values when it is called again and its select options have changed

I'm using bsmSelect jQuery plugin. Basically, what it does is changing the way a select-multiple is rendered to make easier to pick up the options. It hides the select element and shows a list instead.
So, first of all I'm applying the plugin function to my select-multiple element:
$(document).ready(function() {
...
$('#my_select_multiple').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
...
});
On the other way, I have another select element (this one is simple) which has an ajax request bind to its change event. This ajax request get new #my_select_multiple options depending on the select simple value. Ajax response is the new HTML for #my_select_multiple options. So I have:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/
}).responseText;
return r;
}
...
$(document).ready(function() {
...
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val()));
}
...
});
AJAX is working as expected. New options are got correctly and they are inserted into #my_select_multiple (which is hidden by bsmSelect plugin, but I can check it with Firebug). But bsmSelect didn't realize new changes and doesn't get updated.
So, I think what I want is to reapply $('#my_select_multiple').bsmSelect(); with its new options.
I've been looking around a little bit and here is what I have tried.
1. I've tried to call again the funcion with the success and complete (one at time) of the AJAX request. Didn't work:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function() { $('#my_select_multiple').bsmSelect(); }
}).responseText;
return r;
}
2. I've tried to bind the function with the on jQuery function. Didn't work:
$('#my_select_simple').on('change', function() {
$('#my_select_multiple').bsmSelect();
});
3. I've tried 1 and 2 removing previosly the HTML generated by bsmSelect. Didn't work.
Thank you very much.
UPDATE: The exact code
First I have a global.js file which apply bsmSelect plugin to some select multiples (.quizzes):
$('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
And then, in the php file I define the updateQuizzes function and bind it to the select simple (project_id) change event:
<script type="text/javascript">
function updateQuizzes(project_id) {
var r = $.ajax({
type: 'GET',
url: '<?php echo url_for('event/updateQuizzes')?>'+'<?php echo ($form->getObject()->isNew()?'':'?id='.$form->getObject()->getId()).($form->getObject()->isNew()?'?project_id=':'&project_id=')?>'+project_id,
success: function() { $('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
}); }
}).responseText;
return r;
}
$('#project_id').change(function(){
$('.quizzes').html(updateQuizzes($(this).val()));
});
</script>
As I told, the AJAX request works without problems, but not the calling bsmSelect the second time...
Not sure if this is what the problem is, but you could try
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val())).trigger('change');
}
This triggers a change event on select_multiple, and might fire bsmSelect. I'm not sure what the problem here is exactly, but that's the best I can come up with.
I think you want to set your HTML in the success of the Ajax call, something like:
function loadNewOptions(val) {
$.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).bsmSelect();
}
});
}
And then calling like:
$('#my_select_simple').change() {
loadNewOptions($(this).val());
}
$(document).ready(function() {
$('#my_select_simple').change() {
$('#my_select_multiple').load("your Url", function(){
$('#my_select_multiple').bsmSelect();
});
}
});
something like this should work.
.load will put whatever your url returns into #my_select_multiple
the first parameter is the url to load, and the 2nd is a function to call when it is done. which is where you need to set up your fancy selector.
Ok, I opened a ticket and bsmSelect developer has answered me in minutes. Great!
To let bsmSelect know about its select changes, you have to trigger a change event on the select. There is no need to call bsmSelect again.
So it can be that way:
function loadNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).trigger('change');
}
}).responseText;
return r;
}
$('#my_select_simple').change(function() {
loadNewOptions($(this).val());
});

Categories