Request.JSON

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

by jimmyt1001

HTML

<h2>Add a User:</h2>
<input type="text" name="username" placeholder="name">
<input type="email" name="email" placeholder="email">
<button>add user</button>
<h2>Users:</h2>
<ul id="users"></ul>

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

// END YOUR CODE HERE




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