Email Id : phpmk888@gmail.com
Submit form including file upload via jQuery ajax
file uploads over AJAX are a nightmare. I recently had a client ask for file uploads on an AJAX form at the last minute. Scrambling to get it working before deadline I stumbled onto the following method of handling them:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data', 'class' => 'form-horizontal', 'id' => 'form-bulk-upload']]) ?>
<?= $form->field($model, 'userexcelfile')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Upload', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end() ?>
<div id="progress-wrp" style="display: none">
<?php echo Html::img('@web/img/progress.gif', ['class' => 'pull-left img-responsive', 'width'=>'26px']); ?><b>Loading...</b>
</div>
<div class="" id="bult-upload-responce"></div>
<?php
$csrfToken = Yii::$app->request->getCsrfToken();
$script = <<< JS
$(document).ready(function () {
$("#form-bulk-upload").on('beforeSubmit', function (event) {
event.preventDefault();
//grab all form data
//var file_data = $('#excelmodel-userexcelfile').prop('files')[0];
//var form_data = new FormData();
//form_data.append('file', file_data);
var form_data = new FormData($('form')[0]);
$.ajax({
url: '/excel/default/index',
dataType: 'html',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
beforeSend: function() {
$('#progress-wrp').show();
},
success: function(response){
$('#form-bulk-upload')[0].reset();
$('#bult-upload-responce').html(response);
},
complete: function() {
$('#progress-wrp').hide();
},
error: function (data) {
alert("There may a error on uploading. Try again later");
}
});
return false;
});
});
JS;
$this->registerJs($script);
?>
Comments
Post a Comment