Upload image and content using AJAX and Store it in different table

You are viewing revision #5 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#4)next (#6) »

  1. Introduction
  2. How-To Do It

Introduction

We all know how to upload the content and images at the same time with refreshing the page. And uploading the images using Ajax we have faced some issues, here i have fixed the issues and both content and photos are uploaded using Ajax. And both content and images are stored in the different tables

How-To Do It

View:
<?php
	$form=$this->beginWidget('CActiveForm', array(
		'id'=>'post-form',
		'enableAjaxValidation' => FALSE,
		'htmlOptions' => array('enctype' => 'multipart/form-data'),
		));
?>
<div style="display: none;">
	<?php 
             echo $form->fileField($gallery,'forum_image',array('id'=>'forum_image',)); // image file select when clicks on upload photo
        ?>
</div>
<div class="row">
	<?php echo $form->textArea($model,'content',
		array('placeholder'=>"What's going on...!", // placeholder
	 	      'class'=>'status-txt-area', // css style class
		));
	?>
</div>
<div>
       <a href="" onclick="return uploadImage();"><b class="photo">Upload Photo</b></a> <!-- Image link to select imag -->
	<?php echo CHtml::htmlButton('Post',array(
				'onclick'=>'javascript: send();', // on submit call JS send() function
				'id'=> 'post-submit-btn', // button id
				'class'=>'post_submit',
			));
	?>
</div>
<?php $this->endWidget(); ?>

Script:

TO collect the form data and do some validation before and after completion of the uploading the images: Here we use the FormData for collecting the form inputs. FormData is an HTML5 supported object. It's working in all browsers, except IE>9.

<script>
// this script executes when click on upload images link
	function uploadImage() {
	    $("#forum_image").click();
	    return false;
}
</script>

<script type="text/javascript">
// this script for collecting the form data and pass to the controller action and doing the on success validations
function send(){
    var formData = new FormData($("#post-form")[0]);
    $.ajax({
        url: '<?php echo Yii::app()->createUrl("forumPost/uploadPost"); ?>',
        type: 'POST',
        data: formData,
        datatype:'json',
        // async: false,
        beforeSend: function() {
            // do some loading options
        },
        success: function (data) {
        	// on success do some validation or refresh the content div to display the uploaded images 
			jQuery("#list-of-post").load("<?php echo Yii::app()->createUrl('//forumPost/forumPostDisplay'); ?>");
        },

		complete: function() {
            // success alerts
        },

        error: function (data) {
        	alert("There may a error on uploading. Try again later";)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
}
</script>

Then the collected form data are send the the action create and the form will be submitted.

Controller:
public function actionUploadPost() {
        $model = new ForumPost;
	$gallery = new UserGallery;
	if(isset($_POST['ForumPost'], $_FILES['UserGallery'])) {
        // populate input data to $model and $gallery
        $model->attributes=$_POST['ForumPost'];
        $gallery->attributes=$_POST['UserGallery'];
        $rnd = rand(0123456789, 9876543210); 	// generate random number between 0123456789-9876543210
	$timeStamp = time(); 	// generate current timestamp
        $uploadedFile = CUploadedFile::getInstance($gallery, 'forum_image');
        if ($uploadedFile != null) {
		$fileName = "{$rnd}-{$timeStamp}-{$uploadedFile}"; 	// random number + Timestamp + file name
		$gallery -> forum_image = $fileName;
	}
        $valid_format = "jpg,png,jpeg,gif"; 	// Allow the above extensions only.
	if ($gallery -> save() && $valid_format) {
		if (!empty($uploadedFile)) {
			$uploadedFile -> saveAs(Yii::app() -> basePath . '/../images/post/' . $fileName); // save images in given destination folder
                }
        }
        $model -> save(FALSE);
}

done... cheers..

Demo