0

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

Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32
user1763812
  • 437
  • 7
  • 14
  • why two time var data with different values ? – Dimag Kharab Dec 21 '15 at 09:04
  • Sorry about that. I did shorten the code to make it easier to read. That is a typo. – user1763812 Dec 21 '15 at 09:08
  • Note that JS doesn't have the ability to set the default value of a parameter in the function declaration (`save_data(flag = 0)`). See the answer I marked as a duplicate for how to solve your issue. – Rory McCrossan Dec 21 '15 at 09:12
  • Thanks for the reply. I did search for a while before posting and spent time wording my question as briefly as possible. No default value in jquery; thanks. Where cann I find the duplicate question? – user1763812 Dec 21 '15 at 09:17
  • I viewed the duplicate question. It is very informative but I still can't figure out how to adapt the information to my situation. Am I putting the when/then in the wrong location? – user1763812 Dec 21 '15 at 12:20

0 Answers0