I have an function in JavaScript, I try to change an global var from an function but always returns the same initial value 3:
For example: start value 3, function value 0, but always alert 3.
var test = 3;
jQuery.ajax({
type: "POST",
url: "ajax_js.php",
data: String,
success: function(result){
test = result;
if(result == 0){
$('input[name=user_name]').val('');
}
}
});
alert( test);
The A in Ajax means asynchronous.
Your alert is being called before the request is finished, before success
is called and has a chance to update the variable.
Try to move the alert into the callback function and see if that works.
put your var test = 3; outside of the function eg:
<script type="text/javascript">
var test = 3;
$('#button').click(function() {
jQuery.ajax({
type: "POST",
url: "ajax_js.php",
data: String,
success: function(result){
test = result;
alert( test);
if(result == 0){
$('input[name=user_name]').val('');
}
}
});
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With