Hi everyone,
I’m trying to send a Ajax request to send file but Yii remove the post data.
How can I admit my Ajax request into Yii framwork?
P.D: Please I don’t want use CActiveForm because When I send the ajax request refresh entire view.
I have to only send the picture and recover the JSON with the name and id to put on img src
My Form
<form enctype="multipart/form-data" id="photo_form_id"><?php
// echo CHtml::label(Yii::t('common',''),"Photo_title");
echo CHtml::fileField("test",'',array('class'=>'grid-12','id'=>"Photo_title"));
echo CHtml::button(Yii::t('common','Upload'),array('id'=>'upload_photo_button_id','class'=>'grid-4'));
?></form>
My request
var photo_upload_button = $("#upload_photo_button_id");
photo_upload_button.unbind('click');
photo_upload_button.click(function(event){
event.stopPropagation();
var formData = new FormData($('#photo_form_id')[0]);
$.ajax({
url: quoteUrl, //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: update_photo_values,
// error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
// contentType: 'multipart/form-data',
contentType: false,
processData: false
});
e.preventDefault();
});
My controller
public function actionUploadImage()
{
$photo_model=new Photos;
CVarDumper::dump(Yii::app()->request->getParam('test'));
CVarDumper::dump($_POST);
CVarDumper::dump(file_get_contents("php://input"));
if(isset($_POST['Photos']))
{
$photo_model->attributes=$_POST['Photos'];
$photo_model->title=CUploadedFile::getInstance($photo_model,'path');
$photo_model->path=time().'_'.$photo_model->title;
if($photo_model->save()){
...
}
return $photo_model;
}
$id = $photo_model->id;
header('Content-Type: application/json; charset="UTF-8"');
echo json_encode($id);
Yii::app()->end();
}