开发者

update variable after success of ajax function

开发者 https://www.devze.com 2022-12-28 14:49 出处:网络
Hey guys quick question, I am sending a request with the jquery ajax function with a variable. After the request I want that variable updated to match the value of the sent back information, so next t

Hey guys quick question, I am sending a request with the jquery ajax function with a variable. After the request I want that variable updated to match the value of the sent back information, so next time the ajax function executes, it send the value of the new variable.

EDIT

$(document).ready(function()
{
var countusers='<?php echo $countusers; ?>';

function refresh() {

 $.ajax开发者_StackOverflow({
   type: "POST",
   data: "action=refresh_topic&countusers=" + countusers,
   url: "tester.php",
    dataType: 'json',
   success: function(json)
   {
    var countusers=json.countusers;
 }
})
}
setInterval(refresh, 3000);

    });


Your defining the variable inside your success function. Define it outside so it has a global scope then update it inside your success function.

var countusers = 0;
$.ajax({
   type: "POST",
   data: {"countusers": countusers},
   url: "tester.php",
   dataType: 'json',
   success: function(json){
      countusers=json.rownumber;
   }
});


the responce below is correct!

just a notation, since you are using countusers also before it change, it assume that you are setting it also before you call AJAX the first time!

UPDATE:

<head>
<script>
$(function() {

function refresh() {

var countusers = $('#count_my_users').text();

 $.ajax({
   type: "POST",
   data: "action=refresh_topic&countusers=" + countusers,
   url: "tester.php",
   dataType: 'json',
   success: function(json)
   {
    $('#count_my_users').empty().append( json.countusers );
   // var countusers=json.countusers;
 }
})
}

setInterval(refresh, 3000);

    });
</script>
</head>

<body>
<div id="count_my_users"><?php echo $countusers; ?></div>
          <!--/ THIS DIV HOLD USER COUNT /-->
</body>
0

精彩评论

暂无评论...
验证码 换一张
取 消