Codeigniter Tutorials
- What is codeigniter?
- Application_Architecture
- MVC Architecture
- HMVC Architecture
- Codeigniter Configuration
- Remove index.php from url in codeigniter
- MVC Concept
- View
- Alternate PHP Syntax for View Files
- Routing
- Codeigniter URL
- Get Current URL
- Previous page URL get
- Seo Friendly URL
- Slug Create in codeigniter
- What is _remap() function
- Remove controller name from url in codeigniter
- Codeigniter Controller Class
- Class Constructor
- GET $ POST method in Codeigniter
- Models
- Basepath, Apppath, FCPATH
- URI Segment
- Page Redirect
- Helper class
- Custom Helper class
- Form Helper
- Common Helper Functions
- Common Function
- Array Problems
- Call controller in Helper
- Add active class to menu using Helper class
- Custom Library
- Custom Library Example
- when to use get_instance()
- Codeigniter Hook
- how to work inline css in codeigniter
- Custom 404 page
- 404 custom error page
- Create custom config file in codeigniter
- How to set and get config item value
- How to Speed Up CodeIgniter App?
- Codeigniter Functions
- Session
- cookies
- How to Set & Get Tempdata in Codeigniter
- flash messages in Codeigniter
- Flashdata
- Encryption and Decryption In CodeIgniter
- Codeigniter security
- csrf token form security
- Password Hashing
- Form Validation
- Custom Validation
- Registration Form with validation
- Server Side Form Validation
- Validate Select Option Field
- Date Format Validation
- Date Format change in codeigniter
- Date Functions
- DOB Validation
- CI CRUD
- User SignUp
- User Login
- User Logout
- Login Account
- Login form with RememberMe
- Login Form with session
- User change password
- Change Password with Callback Validation to Check Old Password
- Forgot password
- Reset password
- Insert data in database
- Fetch data from database
- Update data in database
- Delete data in database
- File Upload
- Image Upload with resize Image
- Upload Multiple file and images
- Upload Multiple images with CRUD
- File and image update
- Upload Image Using Ajax.
- Email Send
- Email Send Using Email library
- Email Send Using SMTP Gmail
- Notification send
- store data in json format in DB
- Json parse
- Fetch data Using Ajax with Json data
- How to Show data Using Ajax with Json parse
- Get JSON Data from PHP Script using jQuery Ajax
- Insert data Using Ajax
- Submit data Using Ajax with form validation
- How to show data Using Ajax in codeigniter
- Insert & Update Using Ajax
- Registration Form With Validation Using Ajax in codeigniter
- Delete data Using Ajax Confirmation
- Delete All data Using checkbox selection
- Ajax CSRF Token
- Ajax Post
- Ajax serverside form validation
- Contact form using AJAX with form validation
- DataTable Using Ajax dynamically
- DataTables pagination using AJAX with Custom filter
- DataTables AJAX Pagination with Search and Sort in codeigniter
- DataTables in Codeigniter using Ajax
- Ajax Custom Serarch
- Ajax Live Data Search using Jquery PHP MySql
- Ajax Custom Serarch and sorting in datatable
- Dynamic Search Using Ajax
- Autocomplete using jquery ajax
- Jquery Ajax Autocomplete Search using Typeahead
- Dynamic Dependent Dropdown Using Ajax
- Dynamic Dependent Dropdown list Using Ajax
- Dynamic Dependent Dropdown in codeigniter using Ajax
- ajax username/email availability check using JQuery
- Check Email Availability Using Ajax
- Data Load on mouse scroll
- Ajax CI Pagination
- Pagination in codeigniter
- Ajax Codeigniter Pagination
- email exists or not using ajax with json
- CRUD using AJAX With Modal popup in CI
- Add / Show Data on modal popup using Ajax
- Modal popup Validation using Ajax
- Data show on Modal popup Using Ajax
- Add / Remove text field dynamically using jquery ajax
- How to Add/Delete Multiple HTML Rows using JavaScript
- Delete Multiple Rows using Checkbox
- Multiple Checkbox value
- Form submit using jquery Example
- REST & SOAP API
- Multi-Language implementation in CodeIgniter
- How to pass multiple array in view
- Captcha
- create zip file and download
- PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
- data export in excel sheet
- Excel File generate in Codeigniter using PHPExcel
- Dompdf library
- tcpdf library
- Html table to Excel & docs download
- CI Database Query
- Database Query
- SQL Injection Prevention
- Auth Model
- Join Mysql
- Tree View in dropdown option list
- OTP Integration in codeigniter
- curl post
- download file using curl
- Sweet Alert
- Sweet alert Delete & Success
- Log Message in Codeigniter
- Menu & Submenu show dynamically
- Set Default value in input box
- Cron Jobs
- Stored Procedure
- Display Loading Image when AJAX call is in Progress
- Send SMS
- IP Address
- Codeigniter Tutorialspoint
- Website Link
- How To Create Dynamic Xml Sitemap In Codeigniter
- Paypal Payment Integration
- Get Latitude and Longitude From Address in Codeigniter Using google map API
- How To Create Simple Bar Chart In Codeigniter Using AmCharts?
- dynamic Highcharts in Codeigniter
- Barcode in Codeigniter
- Codeigniter Interview Questions
- Project
Home » Codeigniter »
Upload image file using Ajax in codeigniter.
View File
File name : upload_view.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br /><br /><br />
<h3 align="center"></h3>
<form method="post" id="upload_form" align="center" enctype="multipart/form-data">
<input type="file" name="image_file" id="image_file" />
<br />
<br />
<input type="submit" name="upload" id="upload" value="Upload" class="btn btn-info" />
</form>
<br />
<br />
<div id="uploaded_image">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#upload_form').on('submit', function(e){
e.preventDefault();
if($('#image_file').val() == '')
{
alert("Please Select the File");
}
else
{
$.ajax({
url:"<?php echo base_url(); ?>upload_files/ajax_upload",
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
async:false,
success:function(data)
{
alert("Upload Image Successful.");
$('#uploaded_image').html(data);
}
});
}
});
});
</script>
Controller
File Name : Upload_files.php
<?php
defined('BASEPATH') OR exit('no direct script access allowed');
class Upload_files extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('upload_view');
}
public function ajax_upload()
{
if(isset($_FILES["image_file"]["name"]))
{
$config['upload_path'] = './assets/upload/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('image_file'))
{
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
echo '<img src="'.base_url().'assets/upload/'.$data["file_name"].'" width="300" height="225" class="img-thumbnail" />';
}
}
}
}
Upload Image File in Codeigniter Using Jquery Ajax with modal popup.
View Page
File Name :
<html>
<head>
<link rel="stylesheet" href="<?php echo base_url()?>assets/css/bootstrap.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('#frmregister').on('submit', function(e){
e.preventDefault();
var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#name').val();
var mobile = $('#mobileno').val();
var email = $('#email').val();
var partyname = $('#partyname').val();
var profilepic = $('#profilepic').val();
var partylogo = $('#partylogo').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#name').focus();
return false;
}else if(mobile.trim() == '' ){
alert('Please enter your Mobile No.');
$('#mobileno').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#email').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#email').focus();
return false;
}else if(partyname.trim() == '' ){
alert('Please enter party name.');
$('#partyname').focus();
return false;
}else if(profilepic.trim()== ''){
alert('please choose profile image.');
$('#profilepic').focus();
}else if(partylogo.trim()== ''){
alert('please choose party logo.');
$('#partylogo').focus();
}
else{
$.ajax({
type:'POST',
url : '<?php echo base_url();?>home/registermember_ajax',
//data:'name='+name+'&email='+email+'&mobileno='+mobile+'&partyname='+partyname+'&profilepic='+profilepic+'&partylogo='+partylogo,
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
async:false,
success:function(data)
{
alert("Your Candidate Registration Successful.");
$('#frmregister')[0].reset();
$('#register').modal('hide');
}
});
}
});
});
</script>
</head>
<body>
<a href="javascript:void(0)" data-toggle="modal" data-target="#register">PM2019 Registration</a>
<!-- Register Modal -->
<div class="modal fade" id="register" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title w-100 font-weight-bold">PM2019 Candidate Registration</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- <?php //echo base_url();?>home/registermember -->
<form action="" method="post" id="frmregister" name="frmregister" enctype="multipart/form-data">
<p class="statusMsg"></p>
<div class="modal-body mx-3">
<div class="md-form mb-5">
<label data-error="wrong" data-success="right" for="form34">Your name</label>
<input type="text" id="name" name="name" class="form-control validate">
</div>
<div class="md-form mb-5">
<label data-error="wrong" data-success="right" for="form34">Mobile No</label>
<input type="text" id="mobileno" name="mobileno" class="form-control validate">
</div>
<div class="md-form mb-5">
<label data-error="wrong" data-success="right" for="form34">Email</label>
<input type="text" id="email" name="email" class="form-control validate">
</div>
<div class="md-form mb-5">
<label data-error="wrong" data-success="right" for="form34">Party Name</label>
<input type="text" id="partyname" name="partyname" class="form-control validate">
</div>
<div class="md-form mb-5">
<i class="fas fa-user prefix grey-text"></i><label data-error="wrong" data-success="right" for="form34">Profile Image</label>
<input type="file" id="profilepic" name="profilepic" class="form-control validate">
</div>
<div class="md-form mb-5">
<i class="fas fa-user prefix grey-text"></i><label data-error="wrong" data-success="right" for="form34">Party Logo Image</label>
<input type="file" id="partylogo" name="partylogo" class="form-control validate">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary submitBtn">SUBMIT</button>
</div>
</form>
</div>
</div>
</div>
<!-- Register Model -->
</body>
</html>
Controller Method
File Name :
public function registermember_ajax()
{
$candidate_file_name=date("mdY")."_".time();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 1200;
$config['file_name'] = $candidate_file_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('profilepic')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('home', $error);
}
else {
$data = $this->upload->data();
$candidate_image_name = $data['file_name'];
}
$party_logo_name=date("mdY")."_".time();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 1200;
$config['file_name'] = $party_logo_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('partylogo')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('home', $error);
}
else {
$data = $this->upload->data();
$party_logo_name = $data['file_name'];
}
$dataarray = array(
'candidate_name' => $this->input->post('name'),
'mobile' => $this->input->post('mobileno'),
'email' => $this->input->post('email'),
'party_name' => $this->input->post('partyname'),
'candidate_image' => $candidate_image_name,
'election_logo' => $party_logo_name
);
$this->Auth_model->member_register($dataarray);
$this->session->set_flashdata('successmsg', '<div class="alert alert-danger text-center">Registration Successful.</div>');
redirect('home');
}
model method
File Name :
public function member_register($data)
{
$this->db->insert('politician_info', $data);
return;
}
File Name :
Multiple file upload image using ajax
File Name :
<html>
<head>
<title>Multiple File Upload Demo</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="upload.js"></script>
</head>
<form id="fileForm" action="upload.php" enctype="multipart/form-data">
<input type='file' id='uploadfile' name='file[]' multiple />
<button type="button" id="btn_upload">Upload File</button>
</form>
</html>
File Name :
$(document).ready(function(){
$("#btn_upload").click(function(e){
e.preventDefault();
var files = $('#uploadfile')[0].files;
var formData = new FormData();
for(var i=0; i<files.length; i++) {
formData.append('file'+i, $('#uploadfile')[0].files[i]);
}
formData.append('file_count', files.length);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
dataType: "json",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
if(data['upload'] == 'success') {
alert("files uploaded successfully");
} else {
alert(data['upload']);
}
}
});
});
});
File Name : upload.php
<?php
$upload_dir = 'upload/';
for($i = 0; $i < $_POST['file_count']; $i++) {
$file_name = $_FILES['file'.$i]['name'];
$file_tmp = $_FILES['file'.$i]['tmp_name'];
move_uploaded_file($file_tmp, $upload_dir.$file_name);
}
$result['upload'] = 'success';
echo json_encode($result);
File Name :