Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize dynamically created form // Post ajax request

Tags:

jquery

ajax

I have some dynamically created content which includes a little form (dropdown with button) to assign someone to a task.

Using jquery, I want to update my database with the newly assigned person. My approach:

$('#messageDetail').on('click', '#assignButton', function() {
    $.ajax({
        url: "admin_assginMessage.php",
        type: "post",
        data: $("#assignForm").serialize(),
        success: function (data) {
            alert("Success!");
        },
        error: function() {
            alert("Error!");
        }
    });
});

It seems it doesn't send me the form input. I have the feeling that I need to use .on() here, too, but I don't know which event I should choose:

    data: $("#assignForm").serialize(),

Thanks for all answers!

like image 324
Julian Avatar asked Aug 19 '26 13:08

Julian


1 Answers

If you are saying "I created a form as a dynamically, but when I trying to serialize it, I can't see anything about dynamic form's data", the solution is here:

const dynamicForm = `
	<form id="frmData" onsubmit="return false">
	<label>Username
	<input type='text' name='username' />
	</label>

	<label>Password
	<input type='password' name='password' />
	</label>
	<button id="clickSend">Click and Send</button>
	</form>
`;

$("#addForm").on("click", () => {
	$("#frmarea").append(dynamicForm);
})

/* Send Form Details with Dynamic Form */

$(document).on("click", "#clickSend", () => {
	let serializeData = $("#frmData").serialize()
	
	console.log(serializeData)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="frmarea"></div>

<button id="addForm">Add Form</button>

So you should use $(document) when you work with dynamic generated forms.

like image 63
Ali Avatar answered Aug 23 '26 19:08

Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!