Skip to content Skip to sidebar Skip to footer

Upload A File And Reloading A Div Instead Reloading A Page

My last question was related to a bad reloading of a PHP page after uploading a file. Now I have to reload just a div instead of the entire page, and JQuery is not my best friend..

Solution 1:

This is a working example you have to use formData to be able to send files via ajax, this will reload the div and return the server response in <div class="info"></div>

  <form id="uploadFile" enctype="multipart/form-data">
    <h3>Upload a file:</h3>
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" id="submit" value="Upload" name="submit">
  </form>
  <!-- Response Output -->
  <div class="info" style="display:none"></div>
</div>

<div id="updiv">
<form id="uploadFile" enctype="multipart/form-data">
<h3>Upload a file:</h3>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" id="submit" value="Upload" name="submit">
</form>

<!-- Response Output -->
<div class="info" style="display:none"></div>

</div>

<script>
$('#uploadFile').submit(function()
{
  event.preventDefault();
  $("#updiv").fadeOut();
  $.ajax(
  { 
    url: "upload.php",
    type: 'POST',
    data: new FormData(this),
    contentType: false,
    processData: false,
    success: function(data)
    {
      $('.info').html(data);    
      $('.info').show();    
      $("#updiv").fadeIn();
    }
  });

});
</script>

Solution 2:

I suggest you to use blueimp jQuery File Upload

there is a demo php project that you can get the idea from it and here you can learn how to implement it.
and about reload a div part I have no idea what do you mean by that, can you please explain it more?

update:
the output of your upload.php file could be loaded into updiv. in example if you do die('blabla'); in upload.php you can use it as updiv inner html. if you used the jQuery plugin that I mentioned above it would be like this:

<script>
$(function () {
    $('#fileupload').fileupload({
        dataType: 'html', // this could be json too, depends on your needs
        done: function (e, data) { // data.result is whatever returned from your upload.php
            $.each(data.result.files, function (index, file) {
                $('#updiv').html(data.result);
            });
        }
    });
});
</script>

Solution 3:

Using jQuery .serialize() on a multipart form will not send through the file data.

See this answer for more details but essentially you can do

data: new FormData($(this)[0])

instead of

data: $(this).serialize()

Additionally add

processData: false

To the $.ajax object paremeter.

On the subject of testing, have you checked that the form submission and file upload first works correctly if you submit the form without jQuery involved?


Post a Comment for "Upload A File And Reloading A Div Instead Reloading A Page"