I have encountered an issue with a function called onSuccess that is supposed to execute when an AJAX request is successful. The problem is that the function runs as soon as my browser loads, but I want it to only run when a button with the id "myButton" is clicked. Despite using
document.getElementById("myButton");
to locate the button, the console returns a Null result when I execute console.log(document.getElementById("myButton"));
.
I have tried various suggestions from sources indicating that the element might not be in the Document Object Model (DOM) when the script is initiated. However, even after relocating the script and moving the document.getElementById...
line of code, the script still fails to work. While browsing through Stackoverflow for solutions, most of them were based on JQuery, but I am specifically seeking a pure JavaScript solution. Below is my code:
var el = document.getElementById("myButton");
el.onclick = addUser("username", "email", onSuccess);
function onSuccess(result){
alert ('successful');
}
// Do not modify this function. Add user service wrapper.
function addUser(username, email, callback) {
var xhr = new XMLHttpRequest();
var response;
var success = (!!Math.round(Math.random()));
if (!success){
response = JSON.stringify({
success: success,
error: "Oups, something went wrong!"
});
} else {
response = JSON.stringify({
success: success,
user: {
username: username,
email: email
}
});
}
xhr.open("POST", "/echo/json/");
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.send("json=" + response);
};