codiaf
codiaf

Reputation: 629

Upload files with Ajax in CodeIgniter with Jquery not working

I'm trying to make a file upload with Ajax in CodeIgniter but my Jquery code doesn't seem to be getting the data from the form although it seems like the file is in the POST message.

This is my controller:

public function upload_images(){


        $files = $_FILES;



        $data=array();


        if(!empty($_FILES)){



                    $_FILES['userfile']['name']= $files['userfile']['name'];
                    $_FILES['userfile']['type']= $files['userfile']['type'];
                    $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'];
                    $_FILES['userfile']['error']= $files['userfile']['error'];
                    $_FILES['userfile']['size']= $files['userfile']['size']; 


                    $this->upload->initialize($this->set_upload_options());

                    $uploaded=$this->upload->do_upload();



            echo json_encode($data);
        }else{


            echo 'empty';

        }

    }

This is my view:

        <div class="main-content" >

            <h1><?php echo $name=$_POST['name']?></h1>    
            <div class="form-group">


                <?=@$error?>
                <div id="formulario_imagenes">
                    <span><?php echo validation_errors(); ?></span>
                    <?=form_open_multipart(base_url()."index.php/ticketadmin/upload_images",'id="form_upload_front"')?>
                    <input type="file" id="foto1" name="userfile" /><br /><br />
                    <input id="btnsavefront" type="submit" value="Upload" />
                    <?=form_close()?>
                </div>
    </div>
    </div>

The Javascript:

   $(document).on('click','#btnsavefront',function(event){

        //alert('hola  soy el boton guardar');

        //event.preventDefault();

        $('#form_upload_front').submit(function(){

            //event.preventDefault();

            var fileId = document.getElementById('foto1');
            console.log(fileId);
            var formData = new FormData(),
                dir_url='<?php echo site_url('ticketadmin/upload_images');?>';
            formData.append('foto1', fileId.files[0]);

            //console.log(formData);


            $.ajax({
                url: dir_url,
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                /*dataType: "json",*/
                success: function(data){
                    //console.log(data);
                }
            });

        });


        //$('#form_upload_front').submit();

    });

And this is the header from Network

Remote Address:192.168.33.10:80
Request URL:http://fbpostester.com/index.php/ticketadmin/do_upload
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:es-ES,es;q=0.8,en;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:345809
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBV6NO2YxjAQZBFNN
Cookie:ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%222f96b04f42abccfe2403af1c17527312%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A12%3A%22192.168.33.1%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A109%3A%22Mozilla%2F5.0+%28Windows+NT+6.1%3B+WOW64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.143+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1409332543%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D31089f37bfc2cd6b239ad6ef538e1f02e9743309
Host:fbpostester.com
Origin:http://fbpostester.com
Referer:http://fbpostester.com/index.php/ticketadmin/do_upload
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Request Payload
------WebKitFormBoundaryBV6NO2YxjAQZBFNN
Content-Disposition: form-data; name="userfile"; filename="PROPUESTA 2B.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryBV6NO2YxjAQZBFNN--
Response Headersview source
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:840
Content-Type:text/html
Date:Fri, 29 Aug 2014 17:15:50 GMT
Keep-Alive:timeout=5, max=100
Server:Apache
Vary:Accept-Encoding
X-Pad:avoid browser bug
X-Powered-By:PHP/5.3.10-1ubuntu3.13

Upvotes: 0

Views: 7144

Answers (1)

Ahmad
Ahmad

Reputation: 477

Well let me help you,

So here is your form

<form method="POST" class="myForm" enctype="multipart/form-data">
        <!-- add your span and pther stuff here-->
        <input type="file" id="foto1" name="userfile" />
        <input type="button" value="submit" onclick="submitFile();" />
</form>

here is your javascript

function submitFile(){
        var formUrl = "url of your php";
        var formData = new FormData($('.myForm')[0]);

        $.ajax({
                url: formUrl,
                type: 'POST',
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
                success: function(data, textSatus, jqXHR){
                        //now get here response returned by PHP in JSON fomat you can parse it using JSON.parse(data)
                },
                error: function(jqXHR, textStatus, errorThrown){
                        //handle here error returned
                }
        });
}

hope this code was helpfull

Upvotes: 2

Related Questions