SGodoy
SGodoy

Reputation: 763

Ajax not working after creating a Javascript form

I have created a form dynamically using Javascript when i click a button, then i want to proccess the submit event with JQuery and Ajax but it doesn't work, it is redirecting me to the url in action field (blank page by the way) and not triggering the JQuery event. Tried some solutions that i found but still not working.

JS Form

$("#createForm").on("click", function (e) {

    var div = document.getElementById('createTopic');
    var form = document.createElement('form');
    form.setAttribute('id', 'topicForm');
    form.setAttribute('action', "/post/" + postId + "/topic/create");
    form.setAttribute('method', 'POST');

    var csrf = document.createElement('input');
    csrf.setAttribute("type","hidden");
    csrf.setAttribute("name","_token");
    csrf.setAttribute("value",csrf_token);

    var input1 = document.createElement('input');
    input1.setAttribute('type', 'text');
    input1.setAttribute('placeholder', 'Name');
    input1.setAttribute('name', 'topicName');

    var input2 = document.createElement('input');
    input2.setAttribute('type', 'text');
    input2.setAttribute('placeholder', 'Color');
    input2.setAttribute('name', 'topicColor');


    var submit = document.createElement('input');
    submit.setAttribute('type', 'submit');
    submit.setAttribute("value", "Crear");
    submit.setAttribute('id', 'createTopic');

    form.appendChild(csrf);
    form.appendChild(input1);
    form.appendChild(input2);
    form.appendChild(submit);

    div.appendChild(form)
});

Ajax

$("#topicForm").on("submit", function (e) {

    e.preventDefault();
    var form = $(this);

    $.ajax({
        url: form.attr('action'),
        type: "post",
        data: form.serialize(),
        headers: {'X-CSRF-Token': csrf_token},
        success: function (response) {
            console.log("SUCCESS: " + response);
        },
        error: function (jqXHR, exception) {
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
            console.log("ERROR: " + msg);
        },
    });
});

HTML

<div style="float: right;width:150px;">
   <button id=createForm class="btn btn-warning btn-sm"> Add topic <i class="fa fa-plus"></i></button>
</div>

<div id="createTopic" style="float: right;width:150px;"></div>

Upvotes: 0

Views: 121

Answers (1)

Ali Ahmad
Ali Ahmad

Reputation: 439

    $("#createForm").on("click", function (e) {

    var div = document.getElementById('createTopic');
    var form = document.createElement('form');
    form.setAttribute('id', 'topicForm');
    form.setAttribute('action', "/post/" + postId + "/topic/create");
    form.setAttribute('method', 'POST');

    var csrf = document.createElement('input');
    csrf.setAttribute("type","hidden");
    csrf.setAttribute("name","_token");
    csrf.setAttribute("value",csrf_token);

    var input1 = document.createElement('input');
    input1.setAttribute('type', 'text');
    input1.setAttribute('placeholder', 'Name');
    input1.setAttribute('name', 'topicName');

    var input2 = document.createElement('input');
    input2.setAttribute('type', 'text');
    input2.setAttribute('placeholder', 'Color');
    input2.setAttribute('name', 'topicColor');


    var submit = document.createElement('input');
    submit.setAttribute('type', 'submit');
    submit.setAttribute("value", "Crear");
    submit.setAttribute('id', 'createTopic');

    form.appendChild(csrf);
    form.appendChild(input1);
    form.appendChild(input2);
    form.appendChild(submit);

    div.appendChild(form)

    $("#topicForm").on("submit", function (e) {

    e.preventDefault();
    var form = $(this);

    $.ajax({
        url: form.attr('action'),
        type: "post",
        data: form.serialize(),
        headers: {'X-CSRF-Token': csrf_token},
        success: function (response) {
            console.log("SUCCESS: " + response);
        },
        error: function (jqXHR, exception) {
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
            console.log("ERROR: " + msg);
        },
    });
});

});

Upvotes: 1

Related Questions