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
if things way shown, form remains empty
if direct ajax call, within click trigger (not calling function), form filled user's name.
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
Post a Comment