Home:ALL Converter>Passing form values by id in modal

Passing form values by id in modal

Ask Time:2020-11-17T17:37:57         Author:joopeerr

Json Formatter

I have major problem with my jquery and Ajax request as I am new at that.

I am doing CRUD operations and my add method works well. Edit is causing me headache.

I have an edit in mu route like /edit/{id} and whenever button of the modal is clicked, modal is open but on 'save' it's 'undefined'.

U have few problems:

  • ID is not catched.

  • I want to display all current property values of form fields. This is my biggest problem, I saw examples but I was not able to figure out how to display all form field current values based on that ID.

  • Form is passing on submit without any changes

So there are some thing

$(document).on('show.bs.modal', '#editModal', function (e) {
    var id = $(this).data("data-id");
    var startDate = $(this).data("startDate");
    var endDate = $(this).data("endDate");
});

$('#form-edit').on('click', function (e) {
    e.preventDefault();

    var id = $(this).data("id");
    var startDate = $(this).data("startDate");
    var endDate = $(this).data("endDate");

        $.ajax({
            type: 'PATCH',
            url: "/user/edit/"+id,
            data: JSON.stringify({"startDate":startDate, "endDate":endDate}),
            processData: false,
            contentType: 'application/json-patch+json',
            success: function () {
                $("#user-table").load(location.href + " #user-table");
                $('#editModal').modal('hide');
                displayNotif('success', 'check', 'User updated successfully');
            },
            error: function (xhr, status, error) {
                var ErrorMessage = JSON.parse(xhr.responseText);
            }
        });
});

In have defined that id in the modal launch button like:

<a href data-toggle="modal" data-target="#editModal" data-id="{{ user.id }}" class="btn btn-warning user_edit">Edit</a>

Also form is set properly, as add form just with hidden ID field here.

Here is the dorm in modal.

<form class="form" id="user-form" method="post" enctype="multipart/form-data">
   <input type="hidden" name="id" value="">

    <label for="startDate">Start Date: </label>
    <input id="startDate" name="startDate" class="form-control" type="date" value="" required/>

    <label for="endDate">End Date: </label>
    <input id="endDate" name="endDate" class="form-control" type="date" value=""/>
         
    <input id="form-edit" type="submit" class="btn btn-primary" value="Save">
 </form>

I am new with jquery and ajax so any help will be appreciated. Thanks

Author:joopeerr,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/64872688/passing-form-values-by-id-in-modal
yy