JSFiddle - React, Tailwind, and code Playground

by Mykola Senyk

HTML

<h1>List</h1>
<div id="listContainer">Empty</div>
<h2>Application Form:</h2>
<div class="errorMsg"></div>
<form id="person">
    <label>First Name:</label> <input type="text" name="firstName"/><br/>
    Last Name: <input type="text" name="lastName"/><br/>
    Age: <input type="text" name="age"/><br/>
    <input type="submit" value="Add Person"/>
</form>

CSS

div.errorMsg {
    display: none;
    color: red;
    background-color: #e0e0e0;
    padding: 10px;
    width: 300px;
    margin-bottom: 5px;
}

JavaScript

$(function() {
    var url = 'http://premium-api.com/dyn/addPerson';
    // TODO auth call
    
    $('#person').on('submit', function(evt) {
        evt.preventDefault();
        var person = {
            firstName: $('#person input[name=firstName]').val(),
            lastName: $('#person input[name=lastName]').val(),
            age: Number($('#person input[name=age]').val())
        };
        $.post(url, JSON.stringify(person))
        .done(function(data) {
            if ( data.success ) {
                // remove Empty label
                if ( $('#listContainer p').length == 0 ) {
                    $('#listContainer').empty();
                }
                var itemName = person.firstName + ' '
                    + person.lastName + ' ('
                    + person.age + ')'
                ;
                $('<p></p>').text(itemName).appendTo($('#listContainer'));
                // clear all fields
                $('#person input:text').val('');
                $('.errorMsg').hide();
            } else {
                $('.errorMsg').text(data.msg).show();
            }
        })
        .fail(function() {
            // work with exception
            $('.errorMsg').text('Oops! Try again.').show();
        });
    });
});