Problem Manual Ajax Post With Yii Framework

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();

        }



My header

on the file

My post

on the file

My response

I received empty post data. I thought that is because the framework filter this request

My post

on the file

My response

I received empty post data. I thought that is because the framework filter this request

Looks like lyrics to “Sick and tired” by Anastasia :D

Ok, joking apart. You cannot send files via AJAX. Sorry.

Consider using jquery plugins.

thanks for your reply ORey. The problem is the way I was processing the request. I fixed width the next code:

Javascript




        var quoteUrl = ""+<?php echo CJavaScript::encode(Yii::app()->createUrl('photos/uploadImage'));?>;

        $('#Photo_title').fileupload({

            dataType: 'json',

            url: quoteUrl,

            add: function (e, data) {

                var photo_upload_button = $("#upload_photo_button_id");

                photo_upload_button.unbind('click');

                data.context = photo_upload_button.click(function () {

                        data.submit();

                    });

            },

            done: function (e, data) {

                update_photo_values(data.result);

            }

        });

        function update_photo_values(data){

            

            if(data.id > 0){

                $("#Event_photo_id").val(data.id)

            }

            $("#photo_preview_id").attr("src",data.url);

        }



WE HAVE TO USE Uploadhandler to process the request. If we included the process request, you would process right the POST server info properly

EXAMPLE CODE




	public function actionUploadImage()

        {

            require(Yii::app()->basePath . '/../plugins/jquery-file-upload/php/'.'UploadHandler.php');

            $upload_handler = new UploadHandler(null, false,null);

            $data_post      = $upload_handler->post(false);

            $post           = $data_post['files'][0];

            $json           = new stdClass;

            $json->url      = Yii::app()->getBaseUrl(true).'/images/upload/photos/no-image.PNG';

            $json->id       = -1;

            if($post)

            {

                $photo_model        = new Photos;

                $photo_model->title = $post->name;

                $photo_model->path  = $post->name;

                if($photo_model->save()){

                    $json->url      = $post->url;

                    $json->id       = $photo_model->id;

                }

            }

            $upload_handler->head();

            echo json_encode($json);

            Yii::app()->end();

        }



The plugin is here we only need the jquery-fileupload.js

Library jquery-fileupload