使用codeigniter / ajax上传图像 [英] uploading image in a form using codeigniter/ajax

查看:44
本文介绍了使用codeigniter / ajax上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果无法以成功创建的格式上传图像但文件显示0而不是上传文件,我该怎么办。

what should I do if i can't upload an image in a form it successfully created but the file is shows 0 not the upload file. please help me thanks in advance!


脚本,我可以在其中更新并添加带有上载的单个表单

script in view where I can update and add a single form with upload



 <script type="text/javascript">

var save_method; //for save method string
var table;
$(document).ready(function() {
  table = $('#dataTable2').DataTable({ 

    "processing": true, //Feature control the processing indicator.
    "serverSide": true, //Feature control DataTables' server-side processing mode.

    // Load data for the table's content from an Ajax source
    "ajax": {
        "url": "<?php echo site_url('about/ajax_list')?>",
        "type": "POST"
    },

    //Set column definition initialisation properties.
    "columnDefs": [
    { 
      "targets": [ -1 ], //last column
      "orderable": false, //set not orderable
    },
    ],

  });
});

function add_person()
{
  save_method = 'add';
  $('#form')[0].reset(); // reset form on modals
  $('#myModal').modal('show'); // show bootstrap modal
  $('.modal-title').text('Add About US'); // Set Title to Bootstrap modal title
}

function edit_person(about_id)
{
  save_method = 'update';
  $('#form')[0].reset(); // reset form on modals

  //Ajax Load data from ajax
  $.ajax({
    url : "<?php echo site_url('about/ajax_edit/')?>/" + about_id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {

        $('[name="about_id"]').val(data.about_id);
        $('[name="about_details"]').val(data.about_details);
        $('[name="images"]').val(data.image);


        $('#myModal').modal('show'); // show bootstrap modal when complete loaded
        $('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title

    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Error get data from ajax');
    }
});
}

function reload_table()
{
  table.ajax.reload(null,false); //reload datatable ajax 
}

function save()
{
  var url;
  if(save_method == 'add') 
  {
      url = "<?php echo site_url('about/ajax_add')?>";
  }
  else
  {
    url = "<?php echo site_url('about/ajax_update')?>";
  }

   // ajax adding data to database
      $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {

           //if success close modal and reload ajax table
           $('#myModal').modal('hide');
           reload_table();
           if (empty($_FILES['image'])) {          
        return FALSE;
    }
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });
}

function delete_person(about_id)
{
  if(confirm('Are you sure delete this data?'))
  {
    // ajax delete data to database
      $.ajax({
        url : "<?php echo site_url('about/ajax_delete')?>/"+about_id,
        type: "POST",
        dataType: "JSON",
        success: function(data)
        {
           //if success reload ajax table
           $('#myModal').modal('hide');
           reload_table();
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });

  }
}


这是我的表单

This is my form



<div class="modal-body form">

                  <form action="#" id="form">
                   <input type="hidden" value="" name="about_id"/> 
                        <!--                            <div class="form-group has-feedback ">
                                                        <label>Date</label>
                                                        <input type="date" id="date" class="form-control" input-sm placeholder="Date"/>
                                                    </div>-->
                        <div class="form-group has-feedback">
                            <label>About Details</label>
                            <input type="text" id="title" name="about_details" class="form-control" input-sm placeholder="About Details"/>
                        </div>




                        <!-- Description -->

                        <div class="form-group has-feedback">
                           <label>Image</label>
                            <?php $attrib = array('type'=>'text','name'=>'image','class'=>'form-control','id'=>'file'); ?>
        <?php echo form_upload( $attrib,set_value('image')); ?>

                    </form>   

                    <div class="modal-footer">
                        <button type="button"  class="btn btn-default pull-left" data-dismiss="modal">Close</button>
                          <button type="button" id="btnSave" class="btn btn-success"  aria-hidden="true" onclick="save()">Save</button>




我的添加和更新控制器

my controller for add and update



public function ajax_add()
{

    $data = array(
            'about_details' => $this->input->post('about_details'),
            'image' => $this->upload->do_upload('image'),



        );
    $insert = $this->person->save($data);
    echo json_encode(array("status" => TRUE));
}

public function ajax_update()
{
    $data = array(
            'about_details' => $this->input->post('about_details'),
            'image' => $this->upload->do_upload('image'),

        );
    $this->person->update(array('about_id' => $this->input->post('about_id')), $data);
    echo json_encode(array("status" => TRUE));
}


推荐答案

我发现的内容通过CodeIgniter中的ajax上传是当我们提交表单时,图像不会被上传。因此,我使用了一个额外的js文件 jquery.form.min.js,并且ajax上传顺利。要实现它,脚本应如下所示:

What I have found out on uploading through ajax in CodeIgniter is that when we submit the form the images doesn't get uploaded. Because of this I used an extra js file "jquery.form.min.js" and the ajax upload went well. To implement it the script would look like:

$('#uploadimg').ajaxForm({
       //uploadimg is my form id            
        dataType: 'json',
        success: processJson
});
function processJson(data) {
        if(data.msg=="success"){
             alert('Upload is successful.');
        }
        else{
             alert('Upload couldn't be completed.');
        }
}

该表单为

<form action="<?=base_url();?>controller/uploadImage/" method="post" enctype="multipart/form-data" id="uploadimg">

提交时将调用控制器中的uploadImg函数,并在此处保存图像并插入数据库中

On submition this will call the uploadImg function in the controller and here saving the image and insertion in the database is done.

public function uploadImage(){
    //$id = $this->session->userdata('uid');
    $config[ 'upload_path' ]   = UPLOAD_DIR.'/newsletter/0';
    $config[ 'allowed_types' ] = 'gif|jpg|png';
    $config[ 'max_size' ]      = '1500';
    $config[ 'max_width' ]     = '1000';
    $config[ 'max_height' ]    = '1500';
    $image_name                = "files";
    $this->load->library( 'upload', $config );
    if ( $this->upload->do_upload( $image_name ) ) {
            $upload_data = $this->upload->data();
            if(!empty($upload_data)){
                $arg = array(
                            'name' => $upload_data[ 'file_name' ]
                );
                $this->modelName->insert($arg );
                $data['msg']="success";
            }
            else{
                $data['errmsg']="Couldnot upload the file!";
            }
    }
    else{
        $data['errmsg'] =$this->upload->display_errors();
    }
    echo json_encode($data);
}

现在,这将触发脚本中的processJson函数。上载会显示结果。

Now this will trigger the processJson function in the script. And the upload shows the result.

您可以在 jquery.form.js

我希望它对您有用。

这篇关于使用codeigniter / ajax上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆