I have a page with a search button. After hitting the submit button an ajax request is made to get the json from the controller and fill my page with many boxes of products. Each box is a new form with a submit button. I want to be able to submit only one of those new products forms, make some stuff in my DB and the alert success in a div in the very form I submitted. The point is since I don't have my forms initially in the page my script doesn't find any, so how can I attach an ajax function to forms I don't have in the page but that I will have later? And how do I submit a single form in ajax? I tried to use one id for all forms created example and then trying to catch the submit with this code but it doesn't work. The page navigates to my route instead of preventing default and alerting success:
jQuery(function ($) {
$(document).ready(function () {
$(function () {
$('form#dynamic').on('submit', function (e) {
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
alert('success');
}
});
e.preventDefault();
});
});
});
});
I have to add that I already have two forms in the page for searching that are attached to another ajax call, like this:
var form = $(this);
This one works:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "form#dynamic", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
alert('success');
}
});
e.preventDefault();
});
});
});