So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton");
but when I run console.log(document.getElementById("myButton"));
in my browser console I get a Null result.
I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById...
my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My code is below
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);
};