Javascript execution before getting result when ajax call

I have the following code that displays session data. The problem is even if the session matters, and ajax receives this data, the warning I put below the getValFromSession (qes) function call always shows null data. I think this is due to the asynchronous execution of ajax using javascript. So I added extra code as shown in the function
getValFromSession (qid). How can I overcome this asynchronous problem?

var qes=$('#qsid_'+q).val(); var res=getValFromSession(qes); alert(res);//always shows null value $('#select_'+).val(parseInt(res)); function getValFromSession(qid) { return $.ajax({ url : site_url_js+"controller/getValFromSession", type : "POST", data : "qid="+qid, cache: false, async: false }).responseText; } /*controller*/ function getValFromSession() { echo $_SESSION['time'][$_REQUEST['qid']]; } 
0
source share
3 answers

Try the following:

 var qes=$('#qsid_'+q).val(); var res=getValFromSession(qes); function getValFromSession(qid) { $.ajax({ url : site_url_js+"controller/getValFromSession", type : "POST", data : "qid="+qid, cache: false, async: false, success: function(data) { alert(data); // alert here in successHandler $('#select_'+).val(parseInt(data)); } }) } /*controller*/ function getValFromSession() { echo $_SESSION['time'][$_REQUEST['qid']]; } 

Hope this helps.

+3
source

$.ajax provides you with success , error and complete callback handlers. Fill in the response text in these handlers, because the way you performed is synchronous and will be executed immediately, and not after the request is completed.

Documentation

+1
source

You can put your code in a function and call that function on a successful AJAX event, as shown below

 --- --- return $.ajax({ url : site_url_js+"controller/getValFromSession", type : "POST", data : "qid="+qid, false, async: false, success: finalfunction --- --- function finalfunction(res) { alert(res);//always shows null value $('#select_'+).val(parseInt(res)); } 
0
source

Source: https://habr.com/ru/post/1441455/


All Articles