Reputation: 3930
I am trying to import a file with AJAX, using the following plugin -
http://malsup.github.com/jquery.form.js
Based on the following example -
http://malsup.com/jquery/form/progress.html
The my View looks like this -
<form action="/MyController/MyAction" enctype="multipart/form-data" id="myFormId" method="post">
<input type="file" name="file" id="file">
<input type="submit" value="Import File"> </div>
</form>
<script type="text/javascript">
window.onload = function () {
(function () {
$('#myFormId').ajaxForm({
beforeSend: function () {
alert('before send');
},
success: function () {
alert('success');
},
complete: function (xhr) {
alert('xhr.responseText=' + xhr.responseText);
}
});
})();
}
</script>
The javacsript in window.onload = function (){}
is never called. MyAction
is called, and then the browser just displays the JSON Action Result of MyAction
.
Can anyone tell me what I am doing wrong or suggest a different way of doing this? Thanks very much!
Upvotes: 1
Views: 514
Reputation: 1039498
Since the script you wrote is placed after the form, you don't need to be putting it in a window.onload
handler. The following should work fine:
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", id = "myFormId" }))
{
<input type="file" name="file" id="file">
<input type="submit" value="Import File"> </div>
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
(function ($) {
$('#myFormId').ajaxForm({
beforeSend: function () {
alert('before send');
},
success: function () {
alert('success');
},
complete: function (xhr) {
alert('xhr.responseText=' + xhr.responseText);
}
});
})(jQuery);
</script>
Also notice that it is important to make sure that jquery.js is included before the jquery.form.js plugin which needs to be included before the script using it. In the example I have shown I also passed jQuery as parameter to the anonymous function which was being used in order to ensure that there are no conflicts with other plugins you might be using and which might have hijacked the $
function.
Also I would recommend you using a javascript debugging tool such as FireBug or Chrome developer toolbar to ensure that all your scripts are properly included (no 404s) and that you do not have any duplicate scripts or javascript errors.
Upvotes: 3