Search code examples
phpjqueryformsuploadmultipart

Multiple forms with file input on same page


I'm newby with jquery and have a problem with dealing multiple multipart forms on same page. I'm trying to add some data to mysql via php also uploading mp3 files at same time. Each form uses samename+PHPID. There is no problem with first form but im not getting file data when i use other forms. Can anyone help me?

JS:

    $(".msc_send_button").click(function(e) { // changed
     var a = this.id; // Button id
     var form = $('#'+a).parents('form').attr('id'); // Get buttons parent form id
     
        e.preventDefault();
        var formData = new FormData($('#'+form)[0]); // Form Data
         
        $.ajax({
               url: '/formposts',
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false,
                data: formData, 
               beforeSend: function(){
                    // change submit button value text
                    $('#'+a).html('Sending...');
                },
               success: function(data) {
                   if(data) {
                            // Message      
                            $('#info').html(data);
                            //Button Reset
                            $('#'+a).html('Send');
                   }
               },
                error: function(e){
                    alert(e);
                }
        });
        return false;
    });

PHP Form:

    <form name="music-form" id="music-form<?php echo $cont['id']; ?>" enctype="multipart/form-data" novalidate>
    <input type="text" name="songno" id="songno" value="<?php echo $cont['song_no']; ?>">
    <input type="file" id="mp3" name="mp3" class="inputfile" accept="audio/*" multiple>
    <button type="submit" class="msc_send_button" id="msc_send_button<?php echo $cont['id']; ?>">Send</button>
    </form>

Solution

  • I think you should change your jquery selector. I didn't see your html codes but you may have created nested forms. Maybe you can use closest('from') instead of parents('form')

    $(".msc_send_button").click(function(e) { // changed
      
      var buttonEl = $(this);
      var form = buttonEl.closest('form');
    
      e.preventDefault();
      var formData = new FormData(form[0]); // Form Data
    
      $.ajax({
        url: '/formposts',
        type: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        data: formData, 
        beforeSend: function(){
          // change submit button value text
          buttonEl.html('Sending...');
        },
        success: function(data) {
          if(data) {
            // Message      
            $('#info').html(data);
            //Button Reset
            buttonEl.html('Send');
          }
        },
        error: function(e){
          alert(e);
        }
      });
      return false;
    });