I need to upload image with ajax call. But POST field with image always is empty. Part of my form:
<div class="col-lg-6">
<?php echo CHtml::activeFileField($model, 'logo'); ?>
<?php echo CHtml::textField('test', 'test'); ?>
<?php echo CHtml::submitButton('Upload'); ?>
<?php echo CHtml::ajaxSubmitButton('Upload ajax', '#');?>
</div>
If i click submitButton
, then i have both test
and logo
fields - image uploaded.
And if i click ajaxSubmitButton
, then i have only test
field, logo
is empty. What is the solution?
PS: i need non-extension solution.
You cannot upload files with
ajaxSubmitButton
by default. Use simple submit or some uploader. If you want to upload image via ajax, here's example:In your js:
Change Model to your model name and this will work. Also now you can append any data to FormData and it will be passed in $_POST and your file in $_FILES. Be carefull, this way doesn't work on ie7 and ie8 as i remember.
Based on ineersa's answer, I made some improvements:
In your js:
This way you don't have to append each form field manually. All form data will be read automatically (including files). Just make sure that
#model-form
is changed according to your form id.