1

Good day everyone.

I'm making a form with dynamic information to edit certain classes, but when I make the ajax call it doesn't work.

Here is the html with the form:

<form id="userDataForm" name="userDataForm" th:action="@{/admin/addUpdateUser}" th:object="${registerForm}"
          method="post">
        <div id="userDialog" class="modal-dialog" style="margin-left: 25%;">
            <div class="modal-content" style="width: 900px;">
                <div class="modal-header">
                    <h5 class="modal-title theme-color" th:text="#{profile.title}">Crear/editar usuario</h5>

                    <button type="button" class="close" data-dismiss="modal"
                            aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" style="padding: 0px 15px;">
                    <div class="row">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
                            <input type="hidden" name="id" id="id"/>
                            <div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12" style="margin-top: 10px">
                                <input class="form-control" type="text" name="username" id="username"
                                       th:placeholder="#{profile.field.username}" placeholder="Username"
                                       required="required"/>
                            </div>

                            <div id="selectRole">
                                <div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12">
                                    <div style="margin-top: 5px;">
                                        <label for="role" th:text="#{profile.field.rol}"
                                               class="theme-color"
                                               style="font-size: 110%; padding-right: 10px;">Rol</label>
                                        <select class="form-control" id="role" name="role"
                                                data-style="btn-primary" style="display: initial; width: 90%"
                                                required="required" onchange="showManagerOptions(this)">
                                            <option th:each="rol: ${roles}"
                                                    th:text="${rol}" th:value="${rol}">
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="managerInformation" style="display: none;">
                                <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                    <input class="form-control" type="text" name="address" id="address"
                                           th:placeholder="#{profile.field.address}" placeholder="Address"/>
                                </div>
                                <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                    <input class="form-control" type="text" name="city" id="city"
                                           th:placeholder="#{profile.field.city}" placeholder="City"/>
                                </div>
                                <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                    <input class="form-control" type="text" name="postalCode" id="postalCode"
                                           th:placeholder="#{profile.field.postal_code}" placeholder="Postal code"/>
                                </div>
                                <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                    <input class="form-control" type="text" name="areaType" id="areaType"
                                           th:placeholder="#{profile.field.area_type}" placeholder="Area type"/>
                                </div>
                                <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                    <input class="form-control" type="text" name="phoneNumber" id="phoneNumber"
                                           th:placeholder="#{profile.field.phone_number}"
                                           placeholder="Phone number"/>
                                </div>
                            </div>


                            <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                <input class="form-control" type="text" name="firstName" id="firstName"
                                       th:placeholder="#{profile.field.first_name}" placeholder="First Name"
                                       required="required"/>
                            </div>
                            <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                <input class="form-control" type="text" name="lastName" id="lastName"
                                       th:placeholder="#{profile.field.last_name}" placeholder="Last Name"
                                       required="required"/>
                            </div>
                            <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                <input class="form-control" type="email" name="email" id="email"
                                       th:placeholder="#{profile.field.email}" placeholder="Email" required="required"/>
                            </div>
                            <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                <input class="form-control" type="password" name="password" id="password"
                                       th:placeholder="#{profile.field.password}" placeholder="Password"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 pull-right" style="margin-bottom: 10px;">
                        <button class="btn btn-default btn-sm" data-dismiss="modal" aria-hidden="true"
                                th:text="#{common.button.cancel}">Cancel
                        </button>
                        <input type="submit" id="saveUser" class="btn btn-primary btn-sm"
                               th:value="#{common.button.save}" value="Save"/>
                    </div>
                </div>
            </div> <!--.modal-content-->
        </div> <!--.modal-dialog-->
    </form> 

Here the input modal form loader:

function showEditUserModal() {

    if (selectedRow == null) return;

    var idUser = selectedRow.id;
    getInfoUser(idUser);
    var role = $(usersTable.row('.selected').data()[4]).text();

    document.getElementById("selectRole").style.display = "none";
    if (role === 'ROLE_MANAGER') {
        getInfoManager(idUser);
        document.getElementById('managerInformation').style.display = "block";
    } else
        document.getElementById('managerInformation').style.display = "none";
    $('#userModal').modal().show();
}

The ajax calls to fill the inputs:

function getInfoUser(id) {
    var url = appPath + 'admin/userInfo/' + id;
    $.ajax({
        url: url,
        dataType: 'json',
        success: function (user) {
            $('#username').val(user.username);
            $('#firstName').val(user.firstName);
            $('#lastName').val(user.lastName);
            $('#email').val(user.email);
            $('#password').val("");
            $('#role').val(user.role);
        },
        error: function () {
            alert(genericErrorMessage);
        }
    });
}

function getInfoManager(id) {
    var url = appPath + 'admin/managerInfo/' + id;
    $.ajax({
        url: url,
        dataType: 'json',
        success: function (manager) {
            $('#address').val(manager.address);
            $('#city').val(manager.city);
            $('#postalCode').val(manager.postalCode);
            $('#areaType').val(manager.areaType);
            $('#phoneNumber').val(manager.phoneNumber);
        },
        error: function () {
            alert(genericErrorMessage);
        }
    });
}

Until here everything works perfect, I got all the info in the inputs and all, but the submit button, doesn't work, here is the submit function.

$('#userDataForm').submit(function (event) {

    if (!$(this)[0].checkValidity()) {
        $(this).find(':submit').click();
        return false;
    }

    //-- stop submit and do ajax call
    event.preventDefault();
    event.stopPropagation();

    var addUpdateUserUrl = appPath + "admin/addUpdateUser";
    var formData = $(this).serialize();

    $('#userModal').modal('hide');

    $.ajax({
        url: addUpdateUserUrl,
        type: 'POST',
        data: formData
    })
        .done(
            function (resultado, status, jqXHR) {
                if (!status) {
                    alert(genericErrorMessage);
                    return;
                }
                if (resultado == "ok:correct") {
                    document.location.href = appPath + "admin/userlist";
                    return;
                } else if (resultado == "error:login") {
                    document.location.href = appPath + "login";
                    return;
                }
                alert(genericErrorMessage);
                document.location.href = appPath + "admin/userlist";
            })
        .fail(function (jqXHR, status) {
            alert(genericErrorMessage);
            document.location.href = appPath + "admin/userlist";
        });
});

I'm new working with ajax and I'm using bootstrap datatables API, and I'm so confused why it loads but then it doesn't even call the submit function when I click the submit button.

Every idea and help is appreciated.

Thank you everyone!

1 Answers1

1

Probably your function is becoming recursive. You bind .submit() to the form, prevent event propagation, then you try to fire the event "submit" triggering the button. See what is wrong here? I strongly suggest to change listening to the click of the button, then checkValidity(), then post the ajax directly, you don't need an actual form event if you will send it over AJAX.

$('#saveUser').click(function (event) {
//-- stop submit and do ajax call
event.preventDefault();
event.stopPropagation();

if (!$(this)[0].checkValidity()) {
    return false;
}

var addUpdateUserUrl = appPath + "admin/addUpdateUser";
var formData = new FormData($('#userDataForm')[0]);

$('#userModal').modal('hide');

$.ajax({
    url: addUpdateUserUrl,
    type: 'POST',
    data: formData,
    processData: false
})
    .done(
        function (resultado, status, jqXHR) {
            if (!status) {
                alert(genericErrorMessage);
                return;
            }
            if (resultado == "ok:correct") {
                document.location.href = appPath + "admin/userlist";
                return;
            } else if (resultado == "error:login") {
                document.location.href = appPath + "login";
                return;
            }
            alert(genericErrorMessage);
            document.location.href = appPath + "admin/userlist";
        })
    .fail(function (jqXHR, status) {
        alert(genericErrorMessage);
        document.location.href = appPath + "admin/userlist";
    });
});
Marco
  • 2,757
  • 1
  • 19
  • 24
  • 1
    Great! I see the point, I actuaññy changed the .submit to .click and it works, but now I have a problem filling the dataForm, how do you suggest to get this data on the variable? i tried doing var formData = $('#userDataForm').serialize(); and I get all the info properly but fails. – Alejandro Pacheco Tejeda Sep 15 '20 at 20:44
  • Yes, you need to change a bit. Your guess was good, but .serialize() creates a query string, whereas you need a Hash Object with key/value pairs. Check this answer: https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery and please, if it helps you, upvote please. – Marco Sep 15 '20 at 20:56