I am trying to build the page to upload the file by using AJAX, JQUERY and .Net HTTPHandler as in http://dotnet.dzone.com/news/async-file-upload-jquery-and
It works only for the first time I chose a file and uploaded it. But it doesn't work when I select the file next time and doesn't show any error.
If I change the javascript event binding to the old school way like the following, it works perfectly. But I want to use the JQuery Binding. Is there anything I did wrongly? Thanks.
<input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input" onchange="return ajaxFileUpload();">
HTML Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="ID" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<input id="fileToUpload" type="file" size="45" name="fileToUpload" class="fileToUpload" >
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
JQuery Binding Code:
<script>
$().ready(function () {
$(".fileToUpload").change(function() {
$.ajaxFileUpload
(
{
url: 'AJaxUploadHandler.ashx',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
data: { name: 'logan', id: 'id' },
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
console.log(data.error);
} else {
console.log(data.msg);
}
}
},
error: function (data, status, e) {
alert(e);
}
}
)
return false;
});
});
</script>
I had a similar issue. If I tried to upload the exact same file name at the exact same location. Then the change event would basically say no change. I ended up using a click even, checked for $(this).val() and call the the change event inside the click event handler.
The unbind may not be necessary but it works for me.
This has worked for me.
For performance it is better to avoiding using
$(document)
and call the on() method on a wrapper div like this.It has to do with Direct and delegated events: http://api.jquery.com/on/
Use .on method as shown below and try again