0
<?php
    if (!empty($_FILES)){
        echo "<pre>";
        echo $_FILES['file']['type'];
        echo "</pre>";
        return;
    }
?>
<script type="text/javascript">
    function autoUpLoad(){
        $("#txtHint").html("<center><img src='include/images/loader.gif' />Reading selected file...</center>");
        $(document).ready(function(){
            $("#file").change(function(){
                $("#myForm").submit(function(data){
                    $("#txtHint").html(data);
                });
            });
        });
    }
</script>
<form id="myForm" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id = "file" onchange='autoUpLoad()'/>
    <input type="submit" value="Send" />
</form>
<div id="txtHint">
    test
</div>

The above code is not working and I am not sure what is wrong here? It works only if I remove these lines:

function(data){
    $("#txtHint").html(data);
}

It just doesn't allow me to return data to txtHint. Can anyone explain to me how to make it work?

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
Jonathan Chan
  • 553
  • 2
  • 7
  • 12

1 Answers1

2

You are binding a submit event, not fire it.

.submit() method with a callback as parameter is used to bind submit event, without parameter to fire the submit event.

You should do something like below:

$(document).ready(function () {
    $("#myForm").submit(function (data) {
        $("#txtHint").html(data);
    });
    $("#file").change(function () {
        $("#myForm").submit();
    });
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • But the result does not appear in div txtHint. Everything just looks like reload – Jonathan Chan Jul 25 '12 at 06:21
  • 1
    @JonathanChan `.submit` just fire the submit event, and the page will be reload, this is not ajax. – xdazz Jul 25 '12 at 06:25
  • Oh! Is there any ajax function which can solve my problem? I really have hard time learning ajax jquery... – Jonathan Chan Jul 25 '12 at 06:31
  • 1
    @JonathanChan Check this question http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery? – xdazz Jul 25 '12 at 06:32
  • or is there a way to use $.post to send a file? – Jonathan Chan Jul 25 '12 at 06:33
  • @JonathanChan IE7 doest not support html5, you could not use ajax method to upload file. – xdazz Jul 25 '12 at 06:47
  • Found a solution finally Using this ajax form instead http://malsup.com/jquery/form/ function autoUpLoad(){ $(document).ready(function() { var options = { target:'#txtHint' }; $('#file').change(function() { $('#myForm').ajaxSubmit(options); return false; }); }); } – Jonathan Chan Jul 26 '12 at 15:32