I like to upload image using codeigniter Framework in PHP with JQuery AJAX without redirecting the page. When i upload the image it redirecting to controller area and the v
This what i did to solve that problem
HTML
Jquery Ajax
$(function() {
$('#service-provider-details').on('submit', function(e){
var caption = $('#caption').val();
var details = $('#details').val();
var data = new FormData(this);
data.append('caption', caption);
data.append('details', details);
$.ajax({
url:'= base_url(), 'create_profile_sp/upload' ?>',
type:"post",
data: data,
processData:false,
contentType:false,
cache:false,
async:true,
success: function(data){
console.log(data);
}
});
e.preventDefault();
});
});
The controller
class Create_profile_sp extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('profile_sp_m');
}
public function upload($data) {
$data = $_POST;
$this->profile_sp_m->upload_logo($data);
}
}
The model
class profile_sp_m extends CI_Model
{
public $_tablename = 'profiles';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function upload_logo($data) {
$caption = $data['caption'];
$details = $data['details'];
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") ||($_FILES["file"]["type"] == "image/jpg") ||
($_FILES["file"]["type"] == "image/jpeg") ) &&
($_FILES["file"]["size"] < 100000) &&
in_array($file_extension, $validextensions)){
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "
";
} else {
$sourcePath = $_FILES['file']['tmp_name']; Store source path in a variable
$targetPath = "uploads/profiles/" . $_FILES['file']['name']; // The Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath); // Moving Uploaded file
// The Image Data
$imageData = [
'caption' => $caption,
'description' => $details,
];
// Insert the data
$this->db->insert($this->_tablename, $imageData);
}
}
}
}
}