How to upload file using AJAX?

So that's the problem.

I have some form with textFields and file input.

So how can I create a button that will submit all this form?

Does CHtml::ajaxSubmitButton() work?

I'm also trying to do this.

Here is what I have done:

<?php echo CHtml::activeFileField($aluno->pessoa,'foto_file')?>

<?php echo CHtml::ajaxSubmitButton('Enviar',array('rh.pessoaAluno/salvaFoto', 'id'=>$aluno->matricula),array('contentType'=>'multipart/form-data')); ?>

When I check for $_FILES in actionSalvaFoto function it's an empty array.

So is the $_POST.

If I don't set the contentType attribute, $_POST is correct and $_FILES is empty.

This is perhaps an issue with jquery? I'm not sure.

As far as I know, file upload can't be handled with AJAX. In ExtJS they emulate this by creating the <iframe>, duplicating form there and submitting that. Server response is loaded into the iframe and then this response is given to the form submit handler. The only pitfall here is that server should send content-type header when creating response for the iframe form.

And this query will not be an AJAX one, so Yii's check (Yii::app()->request->isAjaxRequest) will give FALSE.

Good to know this. Thank you for explanation.

Here is a fragment from ExtJS docs regarding this:

Quote

File uploads are not performed using normal "Ajax" techniques, that is they are not performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the DOM <form> element temporarily modified to have its target set to refer to a dynamically generated, hidden <iframe> which is inserted into the document but removed after the return data has been gathered.

The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON to send the return object, then the Content-Type header must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.

The response text is retrieved from the document, and a fake XMLHttpRequest object is created containing a responseText property in order to conform to the requirements of event handlers and callbacks.

Be aware that file upload packets are sent with the content type multipart/form and some server technologies (notably JEE) may require some custom processing in order to retrieve parameter names and parameter values from the packet content.