I have a local variable within a function called by a click event. The variable is different depending on which button is clicked.
I'm then trying to pass that variable to another function which contains AJAX.
I can't seem to use the first local variable in the ajax function.
I've tried using "window.myVariable" to make it global but it doesn't work. As you can see in the code I've also added call to the next function with my variable as a parameter but no dice. The error I'm getting in the console is "variable 'user' is not defined."
I cannot access the local variable outside of it's original function at all. Can anyone see why it is refusing to become a global variable?.
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: user + "/process.php",
data: {
'function': 'getState',
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
var user1 = "john";
var user2 = "andrew";
// ============== USER 1 ==============
<button type="button" class="btn btn-info btn-lg chatBtnMain" data-toggle="modal" data-target="#myModal2" id="chatBtn1">
Chat to
<span class='nickname'>
John
</span>
</button>
<script type="text/javascript">
document.getElementById('chatBtn1').addEventListener('click', runScript1);
function runScript1() {
var user = user1;
getStateOfChat(user);
}
</script>
// ============== USER 2 ==============
<button type="button" class="btn btn-info btn-lg chatBtnMain" data-toggle="modal" data-target="#myModal3" id="chatBtn2">
Chat to
<span class='nickname'>
Andrew
</span>
</button>
<script type="text/javascript">
document.getElementById('chatBtn2').addEventListener('click', runScript2);
function runScript2() {
var user = user2;
getStateOfChat(user);
}
</script>