1

I need to submit image with form data,I have search a better method for this, but unfortunately I couldn't find a better way for my purpose, previously done with this.serialize() method. But it doesn't work with images

here is my code

view

 <?php
          $this->load->helper('form');
          $attributes =  array('method'=>'post','name'=>'create_company','id'=>'create_company');
          echo form_open_multipart('',$attributes);?>
    <label>Code : </label> <?php echo form_input('code');?><br/><br/>
    <label>Name : </label> <?php echo form_input('name');?><br/><br/>
    <label>Logo : </label><input type="file" name="userfile"/><br/><br/>
    <label>URL : </label> <?php echo form_input('url');?><br/><br/>
    <label>Description : </label> <textarea name="description" rows="4" cols="50"> </textarea><br/><br/>
    <input type="submit" name="submit" value="Save"/>
    <?php echo form_close(); ?>     
</div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>//no need to specify the language
       $(document).ready(function() {

       $('#create_company').on("submit",function(e) {

            e.preventDefault();

            $.ajax({
                type: "POST",
                url: "<?php echo site_url('site/upload'); ?>",
                data: $(this).serialize(),
                success: function(data){
                    var site_url = "<?php echo site_url('site/create_branch_form'); ?>";
                    var json = $.parseJSON(data);
                    site_url = site_url +"/" + json.results[0].id ;
                    alert(site_url);
                    $("#content").load(site_url);
                    alert(data);
                }
           });            
        });
      });
    </script>

controller

public function upload(){

        //insert company details
    $this->load->model('company_model');
    $data['results'] = $this->company_model->insert_company();
    $this->output->set_output(json_encode($data));                
    }

model

function insert_company(){
        //user details
        $username =  $this->session->userdata('username');
        //$query = $this->db->get_where('userdetails', array('username' => $username));

        $query =  $this->db->get_where('userdetails',array('username'=>$username));

        foreach ($query->result() as $function_info) 
        {
            $this->userid = $function_info->id;
        }

    $new_company_insert_data = array(

        'code' => $this->input->post('code'),
                    'name' => $this->input->post('name'),
                    'logo' => $imgpath['file_name'],
                    'url' => $this->input->post('url'),
                    'description' => $this->input->post('description'),
                    'createdat' => date('Y-m-d H:i:s',strtotime('')),
                    'status' => 0,
                    'userid' => $this->userid
             ); 

        $this->db->insert('companydetails',$new_company_insert_data);
        //get id of the last inserted row
        $this->load->database();
        $query = $this->db->query("SELECT MAX(id) AS id FROM companydetails");
        return $query->result();
}

3 Answers 3

2

Try with FormData object. You should have something like this in your JS code :

 $(document).ready(function() {

   $('#create_company').on("submit",function(e) {
      
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('site/upload'); ?>",
            data: formData,
            cache: false,
            contentType: false,
            processData: false
            success: function(data){
                //function success
            },
            error: function(data){
            //error function
        }
       });            
    });
  });
Sign up to request clarification or add additional context in comments.

5 Comments

how can I move uploaded file into images folder
can I access using post method all fields with text also 'name' => $this->input->post('name'), 'logo' => $imgpath['file_name'],
Yes, all your form fields are encapsulated in the posted object formData.
Yes, you should be able to do that in your controller.
@blackbishop can you help me with call backs too ? i have little issue in ajax
1

Solution 1:

Use FormData object for plain JQuery uploading.

Check this link. It may not work in IE9 browser

Solution 2:

Use this uploader(there are many apart from this) for browser compatibility and more.

Comments

0

Use jquery.form.js for upload form data with attachment. And add this function in controller.

function uploadFile($file, $uploads_dir, $allowfiles) {
        if ($file['size'] > 0) {
            $pic_name = "";
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            if (in_array($ext, $allowfiles)) {
                $pic_name = rand();
                $tmp_name = $file["tmp_name"];
                $pic_name.= $file["name"];
                move_uploaded_file($tmp_name, "$uploads_dir/$pic_name");
            }
            return $pic_name;
        } else {
            return "";
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.