I am using jQuery with PHP/mySql. I have a function, save_data, that saves data and returns a code number by using php and storing information in a database. The function appeared to be working fine.
I then needed to call the function as part of another function. I soon realized that the php/database call was taking time and that I did not get the return code that I needed.
Trying to figure out how to solve this I came across the when/then methods. My intention is that when the user clicks (makeDoc) I would like to get the saveCode before continuing. This is not happening.
I put some alerts into the code to help figure things out. Using the code below, I get the following order of output when clicking makeDoc:
- after call to save_data
- in save data 89MGS4
- undefined
The return code number is valid but is not being returned in time. How can I make get the needed code and then continue the macDoc function?
$('.makeDoc').click(function(){
var saveCode = save_data(1);
alert ("after call to save_data")
alert (saveCode)
});
function save_data(flag = 0){
var somedata = $("#doc-data").val();
var data = {
action: 'save_data',
save_data: somedata
};
$.when(
$.post(the_ajax_script.ajaxurl, data, function(response) {
code_num = response;
})
).then(function() {
if (flag == 1) {
alert ("in save data " + code_num)
return code_num;
}
else if (flag == 0) {
$("#shownum").val(code_num);
}
});
}
Thanks