Reputation: 437
im making a simple script so a piece of code can run in a loop.
var num_rows_php;
var num_rows_sessions_php;
var num_rows_session_php_teste;
$.ajax({
url: 'verify_num_rows.php',
success: function(){
num_rows_php = "<?php echo $my_num_rows; ?>";
num_rows_session_php = "<?php echo $_SESSION['transaction_count']; ?>";
num_rows_session_php_teste = "<?php echo $_SESSION['teste_num']; ?>";
alert('num_rows_session' + num_rows_session_php);
alert('num rows session php teste' + num_rows_session_php_teste);
},
});
alert('teste fora do ajax' + num_rows_session_php_teste);
I only posted the relevant part here, where my problem is. So i create the variables outside the ajax function, so i can update them inside the ajax function. this piece of code is running every 5 seconds, so even if the ajax call isn't made first, the variables should update anytime. My problem is, when i do the Alertsinside the ajax function, the values are correct, but the alert outside the ajax function says the variable is undefined.
alert('teste fora do ajax' + num_rows_session_php_teste);
is undefined, even after the code runs like 10 times. Why is this ?
EDIT :
i tried this:
$.ajax({
url: 'verify_num_rows.php',
success: function(){
num_rows_php = "<?php echo $my_num_rows; ?>";
num_rows_session_php = "<?php echo $_SESSION['transaction_count']; ?>";
num_rows_session_php_teste = "<?php echo $_SESSION['teste_num']; ?>";
alert('num_rows_session' + num_rows_session_php);
alert('num rows session php teste' + num_rows_session_php_teste);
if (num_rows_session_php_teste != num_rows_session_php)
{
alert(num_rows_session_php_teste);
// alert (num_rows_session_php);
$('#tbody').load('table_body.php')
$('#myfooter').load('myfooter.php')
$('#my-list').load('mylist.php')
}
},
});
everything inside ajax success function and the variable is undefined in the moment of the alert.
Upvotes: 0
Views: 1547
Reputation: 790
try adding async: false on your ajax function,
$.ajax({
url: 'verify_num_rows.php',
async: false,
success: function(){
}
})
Upvotes: 1
Reputation: 2528
You cannot expect $.ajax to assign value to num_rows_session_php_teste
. Since JS is async in nature, alert might get invoked before $.ajax takes place. Hence it is possible that num_rows_session_php_teste
is undefined when accessed from alert.
Upvotes: 0