Execute DataTables ajax.reload() Async before a function - javascript

I am trying to source some data from the datatable I am working on. I have an edit button on every row and when is clicked it suppose to bring a form with the data that is already in the table for editing. I need to get real time data when the form is render however ajax.reload() doesn't load the table on time for the form be filled by the correct data and with code below only shows the form for the first employee:
let editEmployeeId;
$(document).ajaxStop(function(){
$('#employeesTable tbody').on('click', '.btn.btn-warning.small-edit-button', function(){
let thisRow = this;
tableEmployees.ajax.reload(function(){
//tableDepartments.draw();
tableDepartments.columns().search("").draw();
//tableEmployees.columns().search("").draw();
getDropdown(1,'#departmentEditDropdown', 'Departments');
var data = tableEmployees.row($(thisRow).parents('tr')).data() || tableEmployees.row($(thisRow).parents('li').attr('data-dt-row')).data();
$('#editFirstName').val(data.firstName);
$('#editLastName').val(data.lastName);
$('#departmentEditDropdown>select').val(data.department);
updateLocation('#locationEditDropdown','#departmentEditDropdown>select');
$('#departmentEditDropdown>select').trigger('change');
$('#locationEditDropdown>select').val(data.locationID);
$('#editJobTitle').val(data.jobTitle);
$('#editEmail').val(data.email);
$('#editEmployeeModal').modal("show");
});
});
I tried:
promise
settimeout
nested functions
async functions
I also try to change ajax call to set async: false and this way it works perfect but I don't think that is a good practice and I have other calls through the document and takes double of time to load the page first time.

I changed the way of calling the button with an extra class for the employees page and used the .click() method instead .on() because for some reason it was going in a loop with the last one. Now works and this is how it looks:
let editEmployeeId;
$(document).ajaxStop(function(){
$('.btn.btn-warning.small-edit-button.employees').click(function(e){
e.preventDefault();
let thisRow = tableEmployees.row($(this).parents('tr'));
let thatRow = tableEmployees.row($(this).parents('li').attr('data-dt-row'));
tableDepartments.columns().search("").draw();
tableEmployees.columns().search("").draw();
getDropdown(1,'#departmentEditDropdown', 'Departments');
tableEmployees.ajax.reload(function(){
var data = thisRow.data() || thatRow.data();
editEmployeeId = data.id;
$('#editFirstName').val(data.firstName);
$('#editLastName').val(data.lastName);
$('#departmentEditDropdown>select').val(data.department);
$('#departmentEditDropdown>select').trigger('change');
$('#editJobTitle').val(data.jobTitle);
$('#editEmail').val(data.email);
$('#editEmployeeModal').modal("show");
})
});

Related

How can I select a DOM element that was created by another event?

The first click event sends an API call that returns several search results.
The second click event should occur when clicks 'upvote', which is an option in each returned search result.
Problem is, it seems that I can't select upvote buttons in search results because they were created (via cloning another element) after the first click event.
Can anyone explain why this happens?
Part of the first click event:
success: function(json) {
var reviews = json.reviews;
$.each(reviews, function(i) {
var critic = reviews[i].critic;
var quote = reviews[i].quote;
var score = reviews[i].original_score;
$('#tile-demo').clone().removeAttr('id').removeClass('hidden')
.find('.critic-name').text(critic).end()
.find('.critic-score').text(score).end()
.find('.critic-quote').text(quote).end()
.appendTo('.review-grid');
}); //end each loop
} //end success call
the new call, which should select a clone of #tile-demo:
$('.search-results').click(function(){
var goodCritic = $(this).siblings('.critic-name').text();
console.log(goodCritic);
});
Use On method as the following:
$('#containerId').on('click','upvotebuttons',function(){write your code here});
where containerId is the id of the container div where you render new data, and replace [upvotebuttons] with [class name] of the upvote buttons.
I just came across a quick screencast by Jeffrey Way that suggests a slightly different solution. The other answer works fine--this is just another way to go about it (still uses event delegation).
$('#parent-of-target').click(function(e) {
if ( $(e.target).is('#target-element') ) {
alert('clicked');
}
});

jQuery Wait for select to populate from database

I have ddl(drop down list) which populates from database after change event of another ddl but I want to change the value of this ddl after it populated from database.
Example:
// This work very well
$("#ddlGroups").on('change',function(){
// Load data from database and populate ddlUsers
// response is loaded from database with $.ajax
// Query Example: SELECT User_ID, Username FROM tblUsers WHERE Group_ID = [Group_ID] (Just for undrestanding the question)
var Records = response.d;
$("#ddlUsers").empty();
$.each(Records, function(){
var _Key = this.User_ID;
_Value = this.Username;
$("#ddlUsers").append($("<option />").val(_Key).text(_Value));
});
});
// When button clicked then trigger ddlGroups change event and assign select option from ddlUsers
var _UserID = User_ID_From_Database; // Loaded from Database when button clicked
$("#ddlGroups").trigger('change'); // Users are loaded from database based on group ID
$("#ddlUsers").val(_UserID); // But this dosn't change
How do I check if ddlUsers is loaded or not, I tried while loop but it never stops.
With jquery there are two main ways (really the same underlying) to connect a ajax response from the database to a event or UI result. The first is promises and the second is a callback. Both these have 1 million examples and jquery documentation is quite robust.
In your case rather than "trigger", you callback calls the right function. The below is just junk code to show.
No: $("#ddlGroups").tigger('change');
Yes:
//Your code
$("#ddlGroups").on('change', updateDDL);
//I have just externalized this function to a scope/place where both the ajax and on change line of code can reference it.
function updateDDL(){
var Records = response.d;
$("#ddlUsers").empty();
$.each(Records, function(){
var _Key = this.User_ID;
_Value = this.Username;
$("#ddlUsers").append($("<option />").val(_Key).text(_Value));
}
};
$.ajax(...., function (data) {
// Update ddl, the existing function you have.
// You should already have something like this.
updateDDL(); //Like this
});
BTW: You could pass the data into the updateDDL directly use $(this) in the updateDDL to improve it etc but that is not key to your question/issue. It seems that you are new to jquery and some of the Javascript features it uses. Take a little time to learn about them and you will be WELL rewarded. I would start by reading examples around ajax/jquery and watch how then update the DOM.

Jquery load content then refresh every 2 second

i am having trouble solving this, i'm trying to load a page which process a variable given by an input form then show the content based on the input, this worked fine, but i am also trying to refresh and update that input every 2 seconds
Below are my codes
<script>
$(document).ready(function(){
function getData(){
$("#dateslot").change(function(){
var inputField= $('#dateslot').val();
$("#timeslot").load('burgerorder_check.php?dateselect='+inputField);
});
setTimeout(getData,1000);
};
getData();
});
</script>
I'm trying to create a function that if someone else picked that, you won't be able to, which i successfully coded but not for the refresh part.
You have the methods and variables in the wrong order. You should probably set a variable outside the getData scope that can change at anytime, then just use that variable when fetching data.
Also, use setInterval if you want to repeat the function. setTimeout is simply a delay.
var val; // the select value is stored here
$("#dateslot").change(function(){
val = $(this).val(); // change the value
}
setInterval(getData,1000);
getData();
function getData(){
if ( val ) {
$("#timeslot").load('burgerorder_check.php?dateselect='+val);
}
}

Jquery delay to stop code like an alert box does

If I use an alert to stop the code running the ddl ‘Suburb1' is populated with the correct value if I use ‘delay’ the value is not set. I need some way of stopping the code running after ‘change’ so that $('#Suburb1').val(SuburbVC); is not fired straight away when the ddl Suburb1 is getting populated from the DB.
if ($(this).attr("checked") == true) {
var PostCode = $('#PostCode').val();
var SuburbVC = $('#SuburbVC').val();
$('#PostCode1').val(PostCode);
// Another function is called which populates Dropdown list from DB
// If I use delay Suburb1 is not populated
$('#PostCode1').change().delay(5000);
//If I use an alert Suburb1 is populated
// alert('delay');
$('#Suburb1').val(SuburbVC);
} else {
$('#PostCode1').val("");
}
Thanks
You are tackling this problem the wrong way; You should add a callback function to execute the rest of the code, after you populate the values from the DB.
How do you populate the values from the DB? AJAX? If so, add a function call with the code you want to execute after the data is ready, to the success handler.

Asp net mvc and javascript response

I had a javascript that needs to do two things:
1. Send data to be updated in database
2. Update my html form place in show mode.
3. Update the row of my table to reflect updated data.
My javascript do only 1 and 2:
$(".form-commands .save").live("click", function () {
var f = $(".form-edit");
var sf = f.serialize();
$.post(this.href,
sf,
function (response) {
f.html(response);
});
// I need to do something here to update the html table row...
return false;
});
I think that a solution is to call another action that will render only the table row elements.
How can I do this?
--
The table row was created something like this:
<tr id="h62">
<td>Ford</td>
<td>Focus</td>
</tr>
where 62 is the "id" of this record.
Working code, but ugly:
$(".form-commands .save").live("click", function () {
var f = $(".form-edit");
var sf = f.serialize();
var handle = $(".form-edit #Handle")[0].value;
var itemLink = this.attributes["edititem"].value;
var row = $("#grid #h" + handle);
$.post(this.href,
sf,
function (response) {
$("#form-edit").html(response);
$.get(itemLink,
sf,
function (response) {
row.replaceWith(response);
});
});
return false;
});
You need to do something like this:
$(".form-commands .save").live("click", function (evt) {
//Capture the jQuery event object and call preventDefault() to stop the default click action
evt.preventDefault();
var f = $(".form-edit");
var sf = f.serialize();
$.post(this.href,
sf,
function (response) {
f.html(response);
});
//UPDATE THE ROWS
$('#h62 td:eq(0)').text(newVehicleMakeName);
$('#h62 td:eq(1)').text(newVehicleModelName);
});
I am not sure from your code where the vehicle data is coming from. If you are passing it back from your controller then you will need to move this line into your success callback.
Also, you should generally never return false, you should capture the jQuery event as a param and call preventDefault(). If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior. This is what was causing your problem, not because you were using click vs submit. The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire.
Well I would just reload the page or recall the ajax routine (whichever is applicable) to reload the data, there is no straightforward method to do this. In fact I was not aware of the method you used (f.html(response)), i am still skeptical about that solution :)
Well, if you really just want to update that single row:
1) You need to know to know the updated row's id in your javascript code. This value is "h62" (without quotes) in this example.
2) Give class names to your TDs, e.g.
<tr id="h62">
<td class="brand">Ford</td>
<td class="model">Focus</td>
</tr>
3) Update using jquery. Let's say you hold the id of the row in a variable named "rowId":
$('#'+rowId).find('.brand').html(response.brand);
$('#'+rowId).find('.model').html(response.model);
This will conclude the process.

Categories