Reputation: 6039
In my JS file i'm calling one function from the other, at first i called it with no arguments by using only it's name handleResponse
Then i tried adding arguments (of course by changing the function signature) and didn't get anything, so i tried calling the function as handleResponse()
and even that didn't work.
Why can't I call my function using brackets or using arguments ?
Here are the functions : The main :
function sendRequest()
{
var username = "";
var game_id = -1;
username = document.getElementById("username").value;
game_id = document.getElementById("game_id").value;
req.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id);
req.onreadystatechange = handleResponse(username, game_id); <--- THIS IS THE CALL
req.send(null);
}
Calling : (I changed the body, it's irrelevant).
function handleResponse(username, game_id) {
if(req.readyState == 4) {
// DO SOMETHING...
}
}
}
Upvotes: 0
Views: 79
Reputation: 12325
You are supposed to set a function reference to onreadystatechange
and not execute the function. You can use closures to achive what you are trying to do.
req.onreadystatechange = function(){
handleResponse(username, game_id);
}
Upvotes: 0
Reputation: 413826
You need to wrap that call in an anonymous function:
req.onreadystatechange = function() {
handleResponse(username, game_id); <--- THIS IS THE CALL
};
The code you posted will call that handler at the point the assignment is made. Instead of that, you need to assign a function that will be called when the ready state changes.
Upvotes: 3