using an ajax function to submit user data with onclick

Viewed 50

Im having trouble understanding this I am trying to use the addUser function to submit user data if the email passes validation. All of this is launched with a button click.

This is the addUser function

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);
};

Heres what i have so far. I have tried calling addUser, creating a success handler for the ajax response, putting in the email and username values. None of it had worked.

function validation() {
    var emailRegex = /^\w+[\w-+\.]*\@\w+([-\.]\w+)*\.[a-zA-Z]{2,}$/;
  var usernameInput = document.getElementById("userName").value;
  var emailInput = document.getElementById("userEmail").value;
  var emailError = document.getElementById('emailErr').textContent = "please enter a valid email address";
  if(!emailRegex.test(emailInput)) {
        emailError
  }
}
function addUserClient() {
    validation();
}

document.getElementById('addUserButton').addEventListener('click', addUserClient);

1 Answers

I'll recommend you to use axios, it's available by a CDN as well. Using it you can handle promises and requests much easily. I'll give you an example in it, since the bare bones implementation of Ajax is too verbose for me, and prone to error (let me know if you need a vanilla JS solution).

function addUser(username, email, callback) {
    // making an ajax post request with axios
    axios.post("/echo/json", {
            // your form fields
            username,
            email
        })
        .then(res => {
            // response from server can be found in res
        })
        .catch(err => {
            // handle any errors here
        );
}
Related