javascript - Ajax setting variable not working in different scopes -


i'm trying set js var using ajax call. var value inputed form element. works fine until point try use var way shown below.

the function use fetch val

function ajaxfetch(query) {   var val;   $.post( "/ajax/crud.php",{mode:"fetch",query:query},function(data) {     val=data;   });   return val; } 

i'll skip crud.php code, since it's working scripts , queries mysql, , echoes value.

then call ajaxfetch function triggered click

$(document).on("click",".btncall",function(){   id=$(this).data("id")//gets id data tag   q1 = "select name user id="+id;   username = ajaxfetch(q1);   $("#form_username").val(username); }); 

what can't understand, guess it's scope issue, following

  1. if things way shown, form remains empty

  2. if direct ajax call, within click trigger (not calling function), form filled user's name.

  3. if things way shown above, add "alert(val)" ajaxfetch function (i use test function), alert "undefined" form filled value.

i ran issue way: first made ajax call within "click" event. created ajaxfetch function, there couple of calls. added "alert" both function , "click" event, see if fetch working properly. first thing i've noticed first alert (inside ajaxfetch) empty, alert inside click event showing value.

thanks in advance. sorry mistakes

edit - way worked (using unwanted alerts)

function ajaxfetch(query) {   var val;   $.post( "/ajax/crud.php",{mode:"fetch",query:query},function(data) {     val=data;      alert(data);    });   return val; }  $(document).on("click",".btncall",function(){   id=$(this).data("id")//gets id data tag   q1 = "select name user id="+id;   username = ajaxfetch(q1);    alert(username)    $("#form_username").val(username); }); 

this way form value will filed. first alert show empty string , second alert show right value.

final edit - working ajax request

function ajaxfetch(query) {   var r;   $.ajax({     type:'post',     url:'/ajax/crud.php',     async:false,     data:{mode:"fetch",query:query},      success: function(response){        r=response;      }   });   return r; } 

this way (adding option "async:false")var filled when ajax finishes it's request. not pro tip, may beginners.

return val inside $.post function liked this.

function ajaxfetch(query) {   var val;   $.post( "/ajax/crud.php",{mode:"fetch",query:query},function(data) {     val=data;     //return statement should here , not out side ajax function     return val;   }); } 

}


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -