
How to submit a form or image using codeigniter, ajax with load button
We can pass all form data using jquery on submit and get all value in codeigniter controller
Step:1
Create an HTML form with your input tag.
<form method="post" name="sub">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="mobile">
<input type="file" name="userfile">
<button type="submit">send</button>
</form>
Step:2
Create jquery function form submit and then after send all form value in codeigniter controller using ajax.
<script type="text/javascript">
$(document).ready(function (e){
$("#sub").on('submit',(function(e){
e.preventDefault();
$('#send').html('Please Wait <i class="fa fa-circle-o-notch fa-spin" style="font-size: 14px;"></i>');
$.ajax({
url: "<?php echo base_url(); ?>Post_ci/upload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
//$("#view").html(data);
},
error: function(){}
});
}));
});
</script>
Step:3
Open your project Application/controller and create a controller class file and create a folder in site root uploads
<?php
class Post_ci extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('Post_model');
$this->load->library('image_lib');
}
public function upload()
{
$config['upload_path'] = './uploads/'; // create folder in site root uploads
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
echo 'no image'
}
$data = array('upload_data' => $this->upload->data());
$img = $data['upload_data']['raw_name'];
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'img'=> $img
);
$query=$this->Post_model->post_data($data);
}// fun
}// class
?>
Step:4
last step to create a model and submit all value in database.
<?php
class Post_model extends CI_Model{
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->database();
}
public function post_data($data){
$this->db->insert('user', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
}
?>
Your database table where you submit all value.
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(11) NOT NULL,
`user_name` varchar(50) NOT NULL,
`user_mobile` varchar(15) NOT NULL,
`img` varchar(100) NOT NULL,
`user_mail` varchar(50) NOT NULL
);
Comments / Answer