Ajax submit modal form in Symfony

In my Symfony project I am trying to write Ajax request for submitted my form that is defined in modal.

I think request is passing but without any results and any errors. I thing problem is in my Ajax request.
Modal opens, I enter all required fields and click ‘submit’, the form is submitted but nothing happens..

<div id="mymodal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
            <div class="modal-body">
                <label for="startDate">Start Date: </label>
                <input id="startDate" name="startDate" class="form-control" type="date"/>
                <label for="endDate">End Date: </label>
                <input id="endDate" name="endDate" class="form-control" type="date"/>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <input id="tag-form-submit" type="submit" class="btn btn-primary" value="Add">
        </div>
        </form>
    </div>
</div>

This are ajax methods that opens my modal and a method for submitting request:

$('#addTag').click(function (e) {
e.preventDefault();
$('#mymodal').modal();
});

$(function () {
    $('#tag-form-submit').on('click', function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: '/me/add',
            data: $('form.tagForm').serialize(),
            processData: false,
            contentType: 'application/json',
            success: function (response) {
                alert(response['response']);
            },
            error: function () {
                alert('Error');
            }
        });
        return false;
    });
});

And in my Controller:

/**
 * @Route("/me/add", methods={"POST"}, name="add")
 */
public function save(Request $request)
{

    $jsonPayload = json_decode($request->getContent(), true);
    $startDate = $jsonPayload['startDate'];
    $endDate = $jsonPayload['endDate'];
    try {
        $this->myService->save($startDate, $endDate); // this method saves data
        return $this->json(["message" => "SUCCESS"]);
    } catch (Exception $e) {
        return $this->json(["message" => $e->getMessage()], Response::HTTP_BAD_REQUEST);
    } 
}

Source: Symfony Questions

Was this helpful?

1 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *