Not Able to Submit a Form Using jQuery On Click method

53 views Asked by At

Using jQuery Form, for some reason I have to submit a form through jQuery on method like this:

$("#submitImage").on("click", function() {
   $('#loaderForm').ajaxForm(function() {
      alert("Uploaded SuccessFully");
   }); 
});

but this is not submitting the form! Can you please take a look at this demo and let me know what i am missing or doing wrong here?

 $("#uploadFile").change(function() {
     $('#image_preview').html("");
     var total_file=document.getElementById("uploadFile").files.length;

     for(var i=0;i<total_file;i++)
     {
        $('#image_preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
     }
  });
  
  $("#submitImage").on("click", function() {
     $('#loaderForm').ajaxForm(function() 
     {
         console.log("Uploaded SuccessFully");
     }); 
});
input[type=file]{
  display: inline;
}
#image_preview{
  border: 1px solid black;
  padding: 10px;
}
#image_preview img{
  width: 200px;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js"></script>
<div class="container">

  <form id="loaderForm" action="uploadFile.php" method="post" enctype="multipart/form-data">
      <input type="file" id="uploadFile" name="uploadFile[]" multiple/>
     
  </form>


  <br/>
  <button type="button" class="btn btn-success" id='submitImage' >Upload Image </button>
  <div id="image_preview"></div>
</div>

2

There are 2 answers

0
xianshenglu On

type of button should be 'submit'

 <button type="submit" class="btn btn-success" id='submitImage' >Upload Image </button>
0
Ahmad On

move the submit button inside the <form> tag and its type should by submit

<form id="loaderForm" action="uploadFile.php" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFile" name="uploadFile[]" multiple/>
  <input type="submit" class="btn btn-success" id='submitImage' value='Upload Image' />
</form>

Otherwise, you can just call $('#loaderForm').submit(); from within the button click event;

<form id="loaderForm" action="uploadFile.php" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFile" name="uploadFile[]" multiple/>

</form>

<button type="button" 
onclick="javascript:function(){ $('#loaderForm').submit(); }"
class="btn btn-success" id='submitImage' >Upload Image 
</button>