0

JavaScript function not wait for ajax function when result return

It immediately shows alerts, after show ajax function result - how to solve this?

my functions

function validate() {

    var companyName=$('#companyName').val();
    var tinNumber=$('#tinNumber').val();
    var panNumber=$('#panNumber').val();
    var address1=$('#address1').val();

    //Company Name
    if(companyName=='')
    {
        $('#companyName').addClass('validationError');
        flag=false;
        return flag;
    }
    else
    {
        flag=checkDuplicateAjax(companyName);
        alert(flag+" 1st");
    }
    alert(flag+" 2nd");

   return flag;
  }

  function checkDuplicateAjax(companyName) 
   {
     var url='<?=base_url() ?>ajax/checkDuplicateAjax';
     $.ajax({
            url:url,
            type:'POST',
            data:dataString,
            dataType:'json',
            success:function(result){
                    console.log(result);
                    alert("success");
                    if(result.status==200)
                    {
                        $('#'+element).val(''); 
                        showMessage(result.message);
                        return false;
                    }
                    else
                    {
                        return true;
                    }

                }
         });
   }
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • when you say "immediately shows alerts" do you see the `alert('success')`? – Ben Lonsdale Jun 05 '17 at 10:48
  • as it is Ajax (async), the execution will not wait for ajax response and execute the next statement. – Shaybi Jun 05 '17 at 10:49
  • you can not return for function in ajax, you can create variable before do ajax, and on ajax you change value variable, you need set `async : false` for ajax – Canh Nguyen Jun 05 '17 at 10:51
  • @MrKen Doing so is not recommended - and in fact it's [already deprecated](https://xhr.spec.whatwg.org/#sync-warning), with browsers logging warnings in the console. – James Thorpe Jun 05 '17 at 10:52

0 Answers0