0

I would like to auto-submit form after image upload. The form is being processed on the same page. so i dont have if(isset($_POST["submit"])) {

<div class="container">
  <h1>jQuery Image Upload 
    <small>with preview</small>
  </h1>
  <div class="avatar-upload">
    <form id="formImageUpload" action="#" method="post" enctype="multipart/form-data">
      <div class="avatar-edit">
        <input type='file' id="imageUpload" name="imageUpload" accept=".png, .jpg, .jpeg" onchange="this.form.submit()"  />
        <label for="imageUpload"></label>
      </div>
    </form>

    <div class="avatar-preview">
      <div id="imagePreview" style="background-image: url(http://i.pravatar.cc/500?img=7);" onchange="this.form.submit()" >
      </div>
    </div>
  </div>
</div>

jquery file is:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
        $('#imagePreview').css('background-image', 'url('+e.target.result +')');
        $('#imagePreview').hide();
        $('#imagePreview').fadeIn(650);
        $("#formImageUpload" ).submit();
    }
    reader.readAsDataURL(input.files[0]);
  }
}


$("#imageUpload").change(function() {   
   readURL(this);
});
3
  • 1
    I think calling onchange="readURL(this)" will do work for you. Commented May 7, 2019 at 9:57
  • Can you please remove # from action : <form id="formImageUpload" action="#" method="post" enctype="multipart/form-data"> and then try to submit Commented May 7, 2019 at 10:07
  • onchange="readURL(this)" did it Commented May 7, 2019 at 11:28

1 Answer 1

1

So, your answer is like this:

<div class="container">
  <h1>jQuery Image Upload <small>with preview</small></h1>
  <div class="avatar-upload">
    <form id="formImageUpload" action="#" method="post" enctype="multipart/form-data">
      <div class="avatar-edit">
        <input type='file' id="imageUpload" name="imageUpload" accept=".png, .jpg, .jpeg" onchange="readURL(this)"  />
        <label for="imageUpload"></label>
      </div>
    </form>

    <div class="avatar-preview">
      <div id="imagePreview" style="background-image: url(http://i.pravatar.cc/500?img=7);" ></div>
    </div>
  </div>
</div>

JS:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#imagePreview').css('background-image', 'url('+e.target.result +')');
      $('#imagePreview').hide();
      $('#imagePreview').fadeIn(650);
      $("#formImageUpload" ).submit();
    }
    reader.readAsDataURL(input.files[0]);
  }
}
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.