javascript - Asynchronous jquery - ajax when().then(); -


i'm new in ajax & jquery , have been trying read documents i'm having hard time understanding concepts:

$.when(function(){                 $.ajax({url:'php/mostrarphp.php', type:'post',data: {quehacer:"mostrarusuarios"}})                 .then(function(success){                      $("#main").html(success);                  },function(error){                      $("#main").html(error);                     });                 })  .then(function(){  console.log("test");  }); 

what i'm trying first function go php file , inside file there include file. after want have console log shown. (this practice when need run functions retrieve data , take longer).

the issue here echo not showing on application, shows resolved on (console.log("test")).

what correct way have execute inside function , second one?

when use $.when, creating new promise, 1 needs resolved. normally, $.when used "combine" multiple promises 1 , run function once all of them resolve.

what you've passed $.when function. function never gets run. docs:

if single argument passed jquery.when() , not deferred or promise, treated resolved deferred , donecallbacks attached executed immediately.

so, means console.log("test"); ran, ajax code never ran.

you not not use $.when here. $.ajax already returns promise, there's no need make one. can chain .then() calls.

$.ajax({     url:'php/mostrarphp.php',     type:'post',     data: {quehacer:"mostrarusuarios"} }).then(function(success){     $("#main").html(success); },function(error){     $("#main").html(error); }).then(function(){     console.log("test"); }); 

edit: in comments said:

[no] matter how time inside execution takes complete, outside [should] execute second

if want, will need create promise. can , have resolve once "inside" function complete. i'd suggest wrapping ajax code in function , having return promise can attach callback to.

function ajaxcall(){     var d = new $.deferred;      $.ajax({         url:'php/mostrarphp.php',         type:'post',         data: {quehacer:"mostrarusuarios"}     }).then(function(success){         settimeout(function(){             $("#main").html(success);             d.resolve();         }, 2000);     },function(error){         $("#main").html(error);         d.reject();     });      return d.promise(); }  ajaxcall().then(function(){     console.log("test"); }); 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -