How can I update a global variable per ajax call? What is happening is that the variable is updated ONLY once. So, The ajax call check if the username exist. If the username exist, I want the variable "username_pass" to equal 0. If the username doesn't exist then "username_pass" to equal 1. What is happening is, if the username_pass fail or pass on the FIRST AJAX CALL, the variable username_pass is updated to either 0 or 1. Well if the username does exist then the user MUST enter a new username. However, on the second, 3rd, ... , n calls; the variable is not updated again and is set to either 0 or 1 from the first call! This is a registration script and each field (username, pass, etc..) variables must be set to 1 in order for the submit button to be viewed!
Can you set up a jsfiddle or post your code so that we can see what is happening in your "success" function
Here's the code: success:function(data){ if(data==0){ store(1) $("#message").html("Username Available"); } else{ store(0) $("#message").html("Username not Available"); } } }); // Store either 1 or 0 for the global variable function store(success){ username_pass = success } Code (markup):
In your function called "store" you save the value to a local variable and not to a global variable. check out http://learn.jquery.com/javascript-101/scope/ if username_pass is defined in the normal part of javascript it should act as a global but there is a school of thought that truely global variables should be attached to the window object
Well when I had it being saved to a global variable it only updates ONLY on the first ajax call. So if the ajax call is successful and the username does not exist then it will be set to one. If the user decides to edit this field again to try a new username, username_pass will remain 1 although the user might enter a username that is already taken. AKA after the first ajax call, the variable is never changed again. var username_pass = 0; success:function(data){ if(data==0){ username_pass = 1; $("#message").html("Username Available"); } else{ username_pass = 0; $("#message").html("Username notAvailable"); } } Code (markup):
Chuck some console.log calls in there to ensure that the extra calls are being made and it's not the ajax that's the problem rather than the global variable.
Ok, so when I add in the console logs after the userpass it works, however, when I try them in other locations, it remains zero or 1. It seems that the variable is only being changed locally instead of globally.
You have to append the success value to the header to make it worked. It's a bit quite complicate though.