Jquery delay to stop code like an alert box does - javascript

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.

Related

Execute DataTables ajax.reload() Async before a function

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

How can I load data from API to page on onload event?

Ajax call using JQuery Ajax call using JQuery
You can store the values in localStorage to retain them and append it to textbox as needed:
$(document).on('ready' ,function(){
var value=localStorage.getItem('symbols'); //get value from localStorage
if(value!="" && typeof value != undefined) //check if it has value or not
$("#inputSymbol").val(value) //set input text's value
$("form").submit(function(){
var valueEnteredByUser = $("#inputSymbol").val();
var valueToBeStored=localStorage.getItem('symbols') + ' ' + valueEnteredByUser;
//here I am storing values with space separate and you have to take care how you want to store it actually
localStorage.setItem('symbols',valueToBeStored); //Store it in same localStorage.
//var valueEnteredByUser = "GE";
if (valueEnteredByUser == null || valueEnteredByUser == ""){
alert("Please enter a valid symbol");
}
new Request.symbolExecution(valueEnteredByUser, function(data) {
$("#dataContainer").remove();
this.success(data);
});
return false;
});
});
Now at any point of time if you want to remove value just do as below:
localStorage.setItem('symbols','') //store empty value
I would make the AJAX call right away inside your $(document).ready() block and push it onto a table that has the style="visibility:hidden;" that way the API call can begin before rendering takes place. Next I would set the hidden table to show during the $(window).load() function (which occurs after 'ready').
It may looks something like this:
$(document).on('ready', function(){
//AJAX API Here
// On success push data to table (hidden style)
});
$(window).load(function(){
//$(.hiddenTable).show();
});
This should provide a good user experience since the data will begin retreival from the API before the page is even rendered.
Why not make the first call through php and then the rest of the keys through js, as you said you want the data that is available through "GE" key as the default, you could get that data by using CURL or get_file_contents().

jQuery and Ajax script

So i have a jQuery script that i should explain it line by line, i already do that and i want to make sure that is correct, so this is my script :
//Here we use the jQuery selector ($) to select the servers_id which is located into
//the delivers_id and we attaches a function to run when a change event occurs
$("#delivers #servers").change(function(){
//Here we look if the servers_id value was changed and the value is different of 0
if($(this).val() != '0') {
//Here we create a new variable sid and we stored the servers_id value in it
var sid = $("#delivers #servers").val();
//Here we use the Ajax $.get to get the sid value and send it by Ajax request then
//we set the data into the o_vmats_id html and empty the vmtas_id
$.get("/deliverability/get_vmtas/" + sid,
function(data) { $('#o_vmtas').html(data); $('#vmtas').html(''); });
}
//Here the else statement, we select the vmtas_id and set the html content like in the code (value=0)
//and empty the o_vmtas_id html content
else { $('#vmtas').html('<option value="0">All Classes</option>');
$('#o_vmtas').html(''); }
});
so please if someone has any remark i will be very appreciative
You're looking for the #servers element twice, no need for that. You can and should cache items that are going to be looked up more than once, so store that element in a var at the very beginning.
Other than that... there's not much to it, other than you wouldn't actually need much jQuery to do this :)

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

Categories