Request.JSON

sending a JSON request to the jsFiddle backend. Later on parse and display the data.

by nimishgoel056

HTML

<h2>Add a User:</h2>
<br />
<p id="error-msg" class="error-text">

</p>
<div class="container">
    <div>
        <label for="username">User Name</label><br />
        <input type="text" id="username" name="username" oninput="onInput(name)" placeholder="name">
    </div>

    <br />

    <div>
        <label for="email">Email</label><br />
        <input type="email" id="email" name="email" oninput="onInput(name)" placeholder="email"><br>
    </div>

    <br />

    <button onclick="onAddUser()">add user</button>

</div>

<h2>Users:</h2>
<ul id="users" class="container">
</ul>

CSS

h2 {
  text-align: center
}

.error-text {
  color: red
}

.input-error {
  background-color: ivory;
  border: none;
  outline: 2px solid red;
}

.container {
  padding: 10px;
  margin: 0 auto;
  width: 80%;
}

ul {
  list-style-type: circle;
}

JavaScript

/*
Assignement:

# HTML
Complete the HTML to have semantic and compliant markups.

# PURE JAVASCRIPT
Dynamically add a user to the users list.
1. Highlight the email input when a user enters an invalid email address and display following message: "please enter a valid email address" in red.
2. Use the addUser function to submit the user's data.
3. If the ajax request returns an error, display the error message in red.
4. Display the newly added user in the users list when the request was successful. 

# BONUS
- make WCAG compliant
- add some CSS3 properties

*/


// START YOUR CODE HERE
function onInput(e) {
    setError("");
    if (e === "email") { setEmailErrorClass(false) }
}



function setEmailErrorClass(addOrRemove) {
    var element = document.getElementById("email");
    const action = addOrRemove ? "add" : "remove"
    element.classList[action]("input-error");
}


function setError(msg) {
    document.getElementById("error-msg").innerText = msg
}

function validateEmail(email) {
    const isValid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)

    if (!isValid) { setEmailErrorClass(true) }


    return isValid;
}

function parseResponse(resp) {
    console.log(resp)
    const { success, user, error } = resp;
    if (success) {
        var ul = document.getElementById("users");
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(user.username + ', ' + user.email));
        ul.appendChild(li);

        document.getElementById("username").value = "";
        document.getElementById("email").value = ""


        setError("")
    } else {
        setError(error)
    }
}

function onAddUser(e) {
    const username = document.getElementById("username").value
    const email = document.getElementById("email").value
    const isValidEmail = validateEmail(email.trim())

    if (!username || !email) {
        return setError("Either Username or Email is missing")
    }

    if (!isValidEmail) {
       ...