upload file using jquery ajax

mehran picture mehran · May 23, 2013 · Viewed 10.7k times · Source

I'm trying to upload a file with jquery but I don't want to refresh the page.

I read some duplicate questions but they didn't solve my problem.

please tell me if I'm wrong in using codes.

<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.form.js" type="text/javascript"></script>
<script src="js/myajax.js" type="text/javascript"></script>

html code:

<form id="uploadpic" action="func/uploader.php" enctype="multipart/form-data" method="post" onsubmit="sendAjax('uploadpic','#image_place'); return false;">
<label for="UserImage" class="fright">new pic</label>
<div class="file-input width-100">
    <input type="file" id="File1" class="choose-file" name="choose-file" onchange="javascript: document.getElementById('uploadpic').submit();" />
    <span class="file-button">- - - - -</span>
</div>
</form>

and myajax.js:

function sendAjax(n,des,dataform){
    if(dataform==undefined) dataform = des;
    $(dataform).animate({opacity:0.5},100);
    var frm = $('#'+n);
        $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
        $(des).html(data);
            $(dataform).animate({opacity:1},100);
        }
    });
    return false;
}

thanks...

Answer

Jyothu picture Jyothu · May 23, 2013

You have to use an ajaxForm submit() function here. Basically I'm a RoR developer. You have to change the Javascript part. (Remove on submit handler from form tag)

Try

<script type="text/javascript">
  $(document).ready(function(){
    $('#File1').change(function() {
      $("#uploadpic").ajaxForm({ target: "#image_view" }).submit();
      return false;
   });
 }); 
</script>

#image_view is just a div. where the response from ajax function can be loaded.