Reputation: 2166
I have the following code which displays session data.The problem am facing is even if the session has value and the ajax get that data the alert that I have put below the function call getValFromSession(qes) always shows null data.I think this is due to the asynchronous execution of ajax with in the javascript.So I put some extra code as shown in the function
getValFromSession(qid).How can I overcome this asynchronous issue?
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']];
}
Upvotes: 0
Views: 243
Reputation: 2467
You can put your code into a function and call that function on success event of AJAX as 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));
}
Upvotes: 0
Reputation: 6003
Try this:
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.
Upvotes: 3
Reputation: 34905
$.ajax
provides you with a success
, error
and complete
callback handlers. Populate your response text in those handlers because the way you have implemented is synchronous and would execute immediately instead of after the request completes.
Upvotes: 1