send binary data with ajax


I’m trying to create a form to save data into db. one of this data is image ( binary data ).

So I have try two approach.

  1. I request it on controller and it worked.

  2. I request it use ajax, but there is some thing wrong, when i saw from firebug.

    on the post tab there is no binary data is sent into server.

This is a spot of my code :

this is locate on my view, i take an approach from ( Thanks Zac, it help me a lot <img src='' class='bbc_emoticon' alt=':)' /> ) 

<?php echo CHtml::ajax(array(


            'data'=> "js:$(this).serialize()",





                if (data.status == 'failure')


                    $('#sdmDialog div#divForForm').html(data.div);

                    // Here is the trick: on submit-> once again this function!

                    $('#sdmDialog div#divForForm form').submit(addSdm);





                    $('#sdmDialog div#divForForm').html(data.div);

                    setTimeout(\"$('#sdmDialog').dialog('close') \",2000);


            } ",


    return false;

This is a piece code locate on my controller, i used it on NON AJAX request ( worked ).

I want to add some NOTE HERE :  on ajax request i just can't save binary data into db, but another data can saved correctly .


                if($img !== null && !$img->getHasError())

                    $model->photo = file_get_contents($img->getTempName());

Thanks a lot

Hope anyone can help me , or give suggestion.

God Bless You

Js don’t work with file upload, I too resined this approach.

Take a look at this post.

You can use sendAsBinary() to upload files via Ajax, though it’s only in FF so depends on your target audience.

I use yahoo library to upload files (With codeigniter!).

Also I find this.

But I did not try to insert files to database.

Hi Zac… Thanks a lot for your respond.

If you don’t mind , do you want to explain what your mean is ? " JS don’t work with file upload" ?

I’m sorry i just new web development,

I have observe from fire bug that there is no binary data sent into server, so am i right that your mean is : $(this).serialize() on my ajax request can’t send binary data although I’ve set ‘enctype’=>‘multipart/form-data’ on my form ?

Thanks a lot

If you don’t mind could you give me a simple example

God Bless You

serialize() won’t get the data from files (yet anyway, sure it will when more browsers can support it) so you need to do a form POST not an ajax one.

Like i mentioned above, sending a file with ajax can be done but as it stands I think it’s only FF that supports what’s needed.


Have you tried this extension eajaxupload/ ? I have not tried it myself. Share with us if it works.