0

I have a script which dynamically generates form elements with their corresponding ID, for e.g.

response from MySQL db says - 4, then

<form ID="form0">
<Input>....
<Button type="submit>....
</form>

<form ID="form1">
<Input>....
<Button type="submit>....
</form>

<form ID="form2">
<Input>....
<Button type="submit>....
</form>

<form ID="form3">
<Input>....
<Button type="submit>....
</form>

once this list of forms are generated, I have an AJAX code which detects the submit buttons and send the input values off to db via PHP page, something like this below,

$(document.body).on('submit', '#form' ,function(e){
e.preventDefault();
var postData = $("#form").serialize();

$.post("../../../functions/processing.php",postData,function(data, status){
  var selectedData = JSON.parse(data);     
  $.each( selectedData, function( i, val ) {
             // do something here...                                           
       });
});
});

So my question is that, for the list of forms, I have to somehow generate multiple of this AJAX code for form0, form1, form2, form3.. and because I can't anticipate how many forms will be generated, I can't just write one AJAX code like the one above.. is there anyway to dynamically generate AJAX codes for dynamically generated multiple forms?

1 Answer 1

1

Give the form a class that identifies it as a form to be handled by your AJAX handler. Then, inside the handler, reference this to get the form element that is being submitted.

<form ID="form0" class="js-ajax-form">
   <input>....
   <button type="submit>....
</form>

Handler

$(document).on('submit', '.js-ajax-form' ,function(e){

    e.preventDefault();
    var postData = $(this).serialize();

    $.post("../../../functions/processing.php",postData,function(data, status){
      var selectedData = JSON.parse(data);     
      $.each( selectedData, function( i, val ) {
                 // do something here...                                           
           });
    });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.