I am new to Yii and ajax I want to read some inputs for a model from view and save it by using ajax. I used the following code inside form
<input type="button" name="save" value="save" onclick="saveFile()" id="profile-update" class="btn button-main" live="false">
and saveFile() is
function saveFile()
{
var data;
data = new FormData();
data.append('file', $('#UserProfile_profile_picture')[0].files[0]);
data.append('UserProfile', $('#profile-update-form').serialize());
$.ajax({
url: '<?php echo CHtml::normalizeUrl(array('user/profileupdate?rand=' . time())); ?>',
type:"POST",
data: data,
processData: false,
contentType: false,
success: function (data) {
$("#AjaxLoader1").hide();
if(data.status=="success"){
$("#formResult1").html("Profile settings changed successfully.");
$("#profile-update-form")[0].reset();
}
else{
$.each(data, function(key, val) {
$("#profile-update-form #"+key+"_em_").text(val);
$("#profile-update-form #"+key+"_em_").show();
});
}
},
beforeSend: function(){
$("#AjaxLoader1").show();
}
}
)
return false;
}
and the code in controller is
$profile = UserProfile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
if (!$profile) {
$profile = new UserProfile;
$profile->create_time = time();
$profile->update_time = time();
}
if (isset($_POST['UserProfile'])) {
$profile->attributes = $_POST['UserProfile'];
$profile->profile_picture=$_FILES['file']['name'];
$images = CUploadedFile::getInstance($profile,'profile_picture');
// print_r($_POST);
// print_r($profile->phone);
// print_r($images);
// exit();
if (isset($images))
{
if(!is_dir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. 'quy'))
{
mkdir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. $profile->profile_picture);
// the default implementation makes it under 777 permission, which you could possibly change recursively before deployment, but here�s less of a headache in case you don�t
}
foreach ($images as $image => $pic)
{
echo $pic->name;if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/profilepic/'.$pic->name))
{
$profile->profile_picture = $pic->name;
}
}
}
$profile->user_id = Yii::app()->user->id;
$profile->update_time = time();
$valid = $profile->validate();
$error = CActiveForm::validate(array($profile));
if ($error == '[]') {
$profile->save(false);
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate(array($profile));
if ($error != '[]')
echo $error;
Yii::app()->end();
exit();
}
}
But here only the profile_picture is saving to the database all other fields are not changing. and the profile picture is not copying into the folder($images is blank) Please somebody help me to solve this problem. Thanks in advance