Can't upload image using ajax in codeigniter - php

I'm trying to upload an image to server but every time i get an error that "you did not select a file to upload"
I have created a form in my View where user details are asked and if candidate option is selected so user would be asked to select an image.
When I'm uploading an image and using jQuery to get a file path i'm getting "C://fakepath/filename.png" but for that also i also configured many things which worked and only return the file name.
I have already created a directory in root folder named upload but still i can't upload any image neither in upload folder nor on server.
View.php
<form method="POST" id="userForm" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-sm-12 col-md-6">
<label>First Name *</label>
<input type="text" name="firstName" class="form-control" value="<?php echo set_value('firstName'); ?>">
<span class="text-danger" id="name_error"><?php echo form_error('firstName'); ?></span>
</div>
<div class="form-group col-sm-12 col-md-6">
<label>Last Name *</label>
<input type="text" name="lastName" class="form-control" value="<?php echo set_value('lastName'); ?>">
<span class="text-danger"><?php echo form_error('lastName'); ?></span>
</div>
</div>
<h5 class="bg-dark text-white p-3 text-center mt-2 mb-4">User Credentials</h5>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" class="form-control" value="<?php echo set_value('email'); ?>">
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<label>Password *</label>
<input type="password" name="password" class="form-control" value="<?php echo set_value('password'); ?>">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="form-group">
<label>Confirm Password *</label>
<input type="password" name="passwordMatch" class="form-control">
<span class="text-danger"><?php echo form_error('passwordMatch'); ?></span>
</div>
<h5 class="bg-dark text-white p-3 text-center mt-2 mb-4">User Status</h5>
<div class="form-group">
<label>User Status *</label>
<select class="form-control" id="userStatus" name="userStatus">
<option value="voter">Voter</option>
<option value="candidate">Candidate</option>
<option value="admin">Admin</option>
</select>
<span class="text-danger"><?php echo form_error('userStatus'); ?></span>
</div>
<div class="form-group" id="candidateSlogan">
<label>Candidate Slogan *</label>
<input type="file" name="userSlogan" class="form-control">
</div>
<button type="submit" class="btn btn-success">Add User</button>
</form>
ajax Response
<script type="text/javascript">
$("#userForm").submit(function(e){
e.preventDefault();
var firstName = $("input[name='firstName']").val();
var lastName = $("input[name='lastName']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
var passwordMatch = $("input[name='passwordMatch']").val();
var userStatus = $("#userStatus").val();
var slogan = $("input[name='userSlogan']").val();
if (userStatus == 'candidate') {
if(slogan == ''){
alert("Please Attach Candidate Slogan");
}
}
$.ajax({
method: 'POST',
url: '<?php echo base_url(); ?>welcome/add_user_validation',
data: {
firstName: firstName,
lastName: lastName,
email: email,
password: password,
passwordMatch: passwordMatch,
userStatus: userStatus,
slogan: slogan
},
success: function(data){
$('#message').html(data);
if(data == 'User Added Successfully'){
$('#message').addClass("alert alert-success");
$('#message').removeClass("alert-danger");
$('#userForm')[0].reset();
$("input[name = 'firstName']").focus();
}
else{
$('#message').addClass("alert alert-danger");
$('#message').removeClass("alert-success");
}
},
error: function(data){
// alert(data);
$('#message').html(data);
}
});
});
</script>
Controller.php
public function add_user_validation(){
// $this->load->helper(array('form', 'url')) // already loaded in autoload.php;
// $this->load->library('form_validation') // declared in autoload.php;
$this->form_validation->set_rules("firstName", "First Name", "required|trim|alpha");
$this->form_validation->set_rules("lastName", "Last Name", "required|trim|alpha");
$this->form_validation->set_rules("email", "Email", "required|trim|valid_email");
$this->form_validation->set_rules("password", "Password", "required");
$this->form_validation->set_rules("passwordMatch", "Password Comfirmation", "required|matches[password]");
$this->form_validation->set_rules("userStatus", "User Status", "required");
if($this->input->post('userStatus') == 'candidate'){
$this->form_validation->set_rules("slogan", "Candidate Slogan", "required");
if(isset($_POST['slogan'])){
$config['upload_path'] = './upload/';
$config['upload_types'] = 'png|jpg|jpeg';
$this->load->library('upload', $config);
echo "<script>alert('hello')</script>";
if($this->upload->do_upload('slogan')){
$candidateSlogan = $this->upload->data();
// print_r($candidateSlogan);
}
else{
// echo $this->upload->display_erorrs();
// echo "This File type is not allowed";
// $candidateSlogan = NULL;
$error = array('error' => $this->upload->display_errors());
echo $error['error'];
// print_r($error);
}
}
}
else{
$candidateSlogan = NULL;
}
if ($this->form_validation->run()) {
$this->load->model('main_model');
$data = array(
"first_name" => $this->input->post('firstName'),
"last_name" => $this->input->post('lastName'),
"email" => $this->input->post('email'),
"password" => $this->input->post('password'),
"user_status" => $this->input->post('userStatus'),
// "slogan" => $this->input->post('userSlogan')
"slogan" => $candidateSlogan
);
// echo "<script>alert(" . $data . ")</script>";
print_r($data);
if($this->main_model->add_user($data)){
echo "User Added Successfully";
}
else{
// $error_msg = $this->db->error();
// echo $error_msg;
echo "User Already Exists";
// echo $this->db->error();
}
}
else{
echo validation_errors();
}
}

you need this in your form tag for files
enctype="multipart/form-data"
the in ajax call add following for files
cache:false,
contentType: false,
processData: false,
and use formdata instead of doing manually for each input
var formData = new FormData(this);
now your ajax should look like this
var formData = new FormData(this); // this will get all inputs from your form
$.ajax({
type:'POST',
url: '<?php echo base_url(); ?>welcome/add_user_validation',
data:formData,
cache:false,
contentType: false,
processData: false,
error: function(data){
console.log("error");
console.log(data);
},
success:function(data){
console.log("success");
console.log(data);
},
});

Related

PHP OOP AJAX, getting errors from Controller

first of all, sorry for my english.
Well, I'm new to OOP PHP. I tried to develope a simple project and I would like to load data with Ajax to view changes without reloading pages.
I don't post models because they work fine and I can get all data I need.
But I have problems sending Controller errors and displaying them to the client.
I have a view called "viewUser.php" = main view.
In the main view is loaded "listUsers.php" in a div by an ajax call to display all the users, than each user has a button to send to another ajax call the id so this last ajax call can populate modal body with all the user informations in a form so they could be modified.
In this way all changes to user informations are displayed without reload the page but only with a ajax call in realtime.
I have this controller:
public function editUsers()
{
$data = [
'id' => '',
'name' => '',
'surname' => '',
'privilege' => '',
'position' => '',
'verified' => '',
'email' => ''
];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$surname = filter_var($_POST['surname'], FILTER_SANITIZE_STRING);
$privilege = filter_var($_POST['privilege'], FILTER_SANITIZE_STRING);
$position = filter_var($_POST['position'], FILTER_SANITIZE_NUMBER_INT);
$verified = filter_var($_POST['verified'], FILTER_SANITIZE_NUMBER_INT);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$data = [
'id' => trim($id),
'name' => trim($name),
'surname' => trim($surname),
'privilege' => trim($privilege),
'position' => trim($position),
'verified' => trim($verified),
'email' => trim($email),
];
$nameValidation = "/^[a-zA-Z]*$/";
//Valida il nome
if (empty($name)) {
$error['nameError'] = 'Perfavore, inserisci il tuo nome!';
} elseif (!preg_match($nameValidation, $name)) {
$error['nameError'] = 'Il nome può contenere solo lettere!';
}
//Controlla che gli errori siano vuoti
if (empty($error['nameError'])) {
$this->userManagementModel->editUser($data);
}
}}
called by ajax
function ajaxEditUser() {
$(document).on("click", "#editUser", function (event) {
event.preventDefault();
var id = $.trim($('#floatingInputId').val());
var name = $.trim($('#floatingInputName').val());
var surname = $.trim($('#floatingInputSurname').val());
var email = $.trim($('#floatingInputEmail').val());
var password = $.trim($('#floatingInputPassword').val());
var confirmPassword = $.trim($('#floatingInputConfirmPassword').val());
var privilege = $.trim($('#floatingSelectPrivileges').val());
var position = $.trim($('#floatingSelectPositions').val());
var verified = $.trim($('#floatingSelectVerified').val());
$.ajax({
url: URLROOT + '/usersManagement/editUsers',
type: 'post',
data: {
id: id,
name: name,
surname: surname,
email: email,
password: password,
confirmPassword: confirmPassword,
privilege: privilege,
position: position,
verified: verified
},
success: function (response) {
// Riaggiorna gli utenti
$(".loadAjax").load(URLROOT + '/usersManagement/listUsers');
$('#closeExampleModal').trigger('click');
}
});
});}
Data is sent from a form in a modal populated by another Ajax request that populates a view loaded into those modal
I would like to view the error generated by controls (if they exist) in editUsers function, into modal
This is ajax call that populates modal:
function ajaxModalUser() {
$(document).on("click", ".btnEditUser", function () {
var userid = $(this).data('id');
// Richiesta AJAX
$.ajax({
url: URLROOT + '/usersManagement/modalUserInfo',
type: 'post',
data: {userid: userid},
success: function (response) {
// Aggiunge il response nel body del modal
$('.modal-body').html(response);
// Apre il modal
$('#exampleModal').modal('show');
}
});
});
}.
here the controller for ajax request for modal:
public function modalUserInfo()
{
$data = [
'users' => '',
'privileges' => '',
'positions' => '',
'noResults' => ''
];
if (isset($_POST['userid'])){
$users = $this->userManagementModel->userInfo($_POST['userid']);
$privileges = $this->userManagementModel->selectPrivileges();
$positions = $this->userManagementModel->selectPositions();
$data = [
'users' => $users,
'privileges' => $privileges,
'positions' => $positions,
'noResults' => 'Nessun risultato'
];
}
$this->view('usersManagement/modalUserInfo', $data);
}
and here the page of the view loaded into modal
<?php
require APPROOT . '/views/includes/head.php';
?>
<div class="container">
<?php if (!empty($data)) {
foreach ($data['users'] as $user) :?>
<form method="post">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputId" name="id" value="<?php echo $user->id;?>" placeholder="id" hidden>
<label for="floatingInputId">Id</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectVerified" name="verified" value="" aria-label="Floating label select example">
<option <?php if ($user->verified == 2){ echo 'selected';} ?> value="2">VERIFICATO</option>
<option <?php if ($user->verified == 1){ echo 'selected';} ?> value="1">NON VERIFICATO</option>
</select>
<label for="floatingSelectVerified">Verifica</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputName" name="name" value="<?php echo $user->name;?>" placeholder="nome">
<label for="floatingInputName">Nome</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputSurname" name="surname" value="<?php echo $user->surname;?>" placeholder="cognome">
<label for="floatingInputSurname">Cognome</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" id="floatingInputEmail" name="email" value="<?php echo $user->email;?>" placeholder="email">
<label for="floatingInputEmail">Email</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingInputPassword" name="password" value="" placeholder="password">
<label for="floatingInputPassword">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingInputConfirmPassword" name="confirmPassword" value="" placeholder="confirm password">
<label for="floatingInputConfirmPassword">Conferma Password</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectPrivileges" name="privileges" value="" aria-label="Floating label select example">
<?php foreach ($data['privileges'] as $privilege) :?>
<option <?php if ($user->privilege_code == $privilege->privilege_code){ echo 'selected';} ?> value="<?php echo $privilege->privilege_code;?>"><?php echo $privilege->privilege;?></option>
<?php endforeach; ?>
</select>
<label for="floatingSelectPrivileges">Privilegi</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="floatingSelectPositions" name="positions" value="" aria-label="Floating label select example">
<?php foreach ($data['positions'] as $position) :?>
<option <?php if ($user->position_id == $position->id){ echo 'selected';} ?> value="<?php echo $position->id;?>"><?php echo $position->user_position;?></option>
<?php endforeach; ?>
</select>
<label for="floatingSelectPositions">Carica</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputCreationDate" name="creationDate" value="<?php if(!is_null($user->creation_date)){echo date("d/m/Y H:i:s", strtotime($user->creation_date));} else { echo "--";} ?>" placeholder="creato il" disabled>
<label for="floatingInputLastUpdate">Data registrazione :</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputLastUpdate" name="lastUpdate" value="<?php if(!is_null($user->last_update)){echo date("d/m/Y H:i:s", strtotime($user->last_update));} else { echo "--";} ?>" placeholder="ultimo aggiornamento" disabled>
<label for="floatingInputLastUpdate">Ultima modifica :</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputLastLogin" name="lastLogin" value="<?php if(!is_null($user->last_login)){echo date("d/m/Y H:i:s", strtotime($user->last_login));} else { echo "--";} ?>" placeholder="ultimo login" disabled>
<label for="floatingInputLastLogin">Ultimo login :</label>
</div>
</form>
<?php endforeach;
}?>
</div>
I tried many solutions, but I can't understand how send the error to the view of the modal and reloading it into modal.
Thanks to everybody

Update Data with Bootstrap Modal using CodeIgniter and Ajax

I'm trying to figure it out why I can't get the alert warning or success from the form validation in a modal. all I want at first is to update the data in the database and it work. now I can't see the alert whether it is wrong or correct, the modal close after I submit and how can I transfer the echo json_encode to alert in modal
view: layout view
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if (data.result){
$('#result').html('<p class="alert-success"> The inputs are insufficient </p>');
}else{
$('#result').html('<p class="alert-warning"> The profile successfully updated</p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="profile" id="1" href="#Profile_modal" data-toggle="modal">Profile</a>
<div class="modal" id="Profile_modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg modal-dialog-scrollable" >
<div class="modal-content">
<div class="modal-header bg-secondary">
<h5 class="modal-title text-white">Profile</h5>
<button type="button " class="close" data-dismiss="modal" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" >
<div class="text-center" id="result"> </div>
<div id="data_profile"> </div>
</div>
</div>
</div>
</div>
Controller: profile/profile_update
public function profile_update(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[13]');
$this->form_validation->set_rules('contact', 'Contact', 'trim|required|min_length[11]');
$this->form_validation->set_rules('hoax', 'Password',
'trim|required|min_length[6]|matches[confirm]');
$this->form_validation->set_rules('confirm', 'ConfirmPassword', 'trim|required|min_length[6]');
if ($this->form_validation->run() == FALSE) {
$data = array('profile_errors' => validation_errors());
echo json_encode(array("result"=>false));
}else{
$this->load->model('admin_model');
$data=$this->profile_model->update_data();
//$data = 'Your Profile Data has been Updated Successfully';
echo json_encode(array("result"=>true));
}
}
profile/get_fetchdata()
public function get_fetchdata(){
$Admin_id = $this->input->post('Admin_id');
if(isset($Admin_id) and !empty($Admin_id)){
$records = $this->profile_model->fetch_data($Admin_id);
$output = '';
foreach ($records->result_array() as $row) {
$attributes = array('id'=>'login_form', 'class'=>'form');
$output = '<div class="text-center" id="result"> </div>';
echo form_open('profile/profile_update', $attributes);
$output = '
<div class="form-group text-left">
<label> Username </label>
<input type="text" id="username" class="form-control" value='. $row["username"] .' placeholder="Enter Username" name="username" maxlength="10" required>
</div>
<div class="form-group text-left">
<label> Email </label>
<input type="Email" id="email" class="form-control" value='. $row["email"] .' placeholder="Enter Email" name="email" maxlength="20" required>
</div>
<div class="form-group text-left">
<label> Phone Number</label>
<input type="number" id="contact" class="form-control" value='.$row["contact"].' placeholder="Enter Phone Number" name="contact" maxlength="11" required>
</div>
<div class="form-group text-left">
<label> Password </label>
<input type="password" id="hoax" class="form-control" value='. $row["hoax"].' placeholder="Enter Password" name="hoax" maxlength="15" required>
</div>
<div class="form-group text-left">
<label> Confirm Password </label>
<input type="password" id="confirm" class="form-control" value='.$row["hoax"].' placeholder="Confirm Password" name="confirm" maxlength="15" required>
</div>
<input type="hidden" id="Admin_id" class="form-control" value='. $row["Admin_id"] .' name="Admin_id">
<input type="hidden" id="date" class="form-control" value='. $row["date_modified"] .' name="date">
<button class="btn btn-primary float-right new_profile" id="1" name="submit" type="submit" >Save</button>
<button class="btn btn-danger mx-2 float-right" data-dismiss="modal" type="button"> Cancel </button>';
echo form_close();
}
echo $output;
}else {
echo "Nothing to show";
}
}
if you use json as dataType, the browser will wait always for a JSON response, so the best thing to do here is the following:
if($this->form_validation->run() == FALSE){
echo json_encode(array("result" => false, "message" => "Failed"));
}else{
echo json_encode(array("result" => true, "message" => "Success!"));
}
and you can check the results on ajax side by using:
$('#login_form').on('submit', function( event ){
event.preventDefault();
var Admin_id = $('#Admin_id').val();
var username = $('#username').val();
var email = $('#email').val();
var contact = $('#contact').val();
var hoax = $('#hoax').val();
var confirm = $('#confirm').val();
var date = $('#date').val();
$.ajax({
url: "<?php echo base_url('profile/profile_update'); ?>",
method: "POST",
data: {Admin_id:Admin_id, username:username, email:email,
contact:contact, confirm:confirm, date:date, hoax:hoax},
dataType: "json",
success: function(data){
if(data.result){
$('#adminId').val("");
$('#username').val("");
$('#email').val("");
$('#contact').val("");
$('#hoax').val("");
$('#confirm').val("");
$('#date').val("");
$('#result').html('<p class="alert-success"> ' + data.message + ' </p>');
}else{
$('#result').html('<p class="alert-warning"> ' + data.message + ' </p>');
}
//return false;
//event.preventDefault();
}
});
return false;
//event.preventDefault();
});

How to upload image in codeigniter using ajax

Here is my code,
Please check this, Iam trying to upload image its not working. Iam passing data through ajax using id.
Iam getting image name, while passing through codeigniter its showing error undefined user_img
Below code is Ajax
$('#profile_set').validate({
submitHandler: function(form) {
user_zip = $("#user_zip").val();
first_name = $("#xx_first_name").val();
db_email = $("#db_email").val();
datepicker = $("#datepicker").val();
last_name = $("#xx_last_name").val();
new_image = $("#new_image").val();
$.ajax({
url: "<?php echo base_url('myaccount/profile/'.$this->session->userdata('id').''); ?>",
type: "post",
fileElementId :'new_image',
dataType: 'json',
data: {
xx_first_name: first_name,
xx_last_name: last_name,
db_email: db_email,
db_dob: datepicker,
user_zip: user_zip,
user_img: new_image
},
success: function (data) {
if(data.status == 'success'){
$('#message').removeClass('alert alert-danger');
$('#message').addClass('alert alert-success');
$('#message').empty();
$('#message').append(data.message);
$('#message').fadeOut(3000);
}
else if(data.status == 'fail') {
$('#message').removeClass('alert alert-success');
$('#message').addClass('alert alert-danger');
$('#message').empty();
$('#message').append(data.message);
}
}
});
}
});
In this function am getting image name, Its showing undefined index of profile_img['file_name' => $_FILES['user_img']['name'] ]
public function profile($id)
{
$user_id = $id;
$profile_img = $this->input->post('user_img');
if ($user_id !== '' AND $user_id > 0) {
if(!empty($profile_img)){
$uploadconfig = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '204800',
'file_name' => $_FILES['user_img']['name'],
'encrypt_name' => TRUE
);
print_r($uploadconfig); exit;
$this->load->library('upload', $uploadconfig);
if ( ! $this->upload->do_upload("user_img")) {
echo "failed to upload file(s)";
}
$this->upload->initialize($uploadconfig);
$this->upload->do_upload("user_img");
$upload_data = $this->upload->data();
$user_profile = $upload_data['file_name'];
$data = array();
$data['first_name'] = $this->input->post('xx_first_name');
$data['last_name'] = $this->input->post('xx_last_name');
$data['email'] = $this->input->post('db_email');
$data['user_dob'] = $this->input->post('db_dob');
$data['user_zip'] = $this->input->post('user_zip');
$data['user_img'] = $user_profile;
}
else {
$data = array();
$data['first_name'] = $this->input->post('xx_first_name');
$data['last_name'] = $this->input->post('xx_last_name');
$data['email'] = $this->input->post('db_email');
$data['user_dob'] = $this->input->post('db_dob');
$data['user_zip'] = $this->input->post('user_zip');
}
$update_set = $this->users->update($id, $data);
if ($update_set)
{
$ret['status'] = 'success';
$ret['message'] = 'Updated successfully';
echo json_encode($ret);
}
else
{
$ret['status'] = 'fail';
$ret['message'] = 'Error while updating';
echo json_encode($ret);
}
}
}
My forum Code
<div class="account_forum" id="profile">
<h2 class="forum_title">Profile</h2>
<form id="profile_set">
<div class="row row_space">
<div class="col-md-10">
<a class="profile-pic" id="existing_pic">
<div class="profile-pic" style="background-image: url('<?php echo base_url('uploads/')?><?php echo #$users->user_img ?>')" >
<span class="glyphicon glyphicon-camera"></span>
<span>Change Image</span>
</div>
</a>
<input type='file' name="new_image" id="new_image" onchange="readURL(this);" style="display:none;" />
<a class="profile-pic" id="new_upload">
<div class="profile-pic" id="view_image">
<span class="glyphicon glyphicon-camera"></span>
<span>Change Image</span>
</div>
</a>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>First Name</label>
<input type="text" name="xx_first_name" id="xx_first_name" class="form-control" placeholder="John" value="<?php echo set_value('xx_first_name', #$users->first_name);?>" required>
</div>
<div class="col-md-5">
<label>Last Name</label>
<input type="text" name="xx_last_name" id="xx_last_name" class="form-control" placeholder="Doe" value="<?php echo set_value('xx_last_name', #$users->last_name);?>" required>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>Email</label>
<input type="text" name="db_email" class="form-control" id="db_email" placeholder="jdoe#gmail.com" value="<?php echo set_value('db_email', #$users->email);?>" required>
</div>
<div class="col-md-5">
<label>Birthday</label>
<input type="text" name="db_dob" class="form-control" data-toggle="datepicker" placeholder="00/0/0000" id="datepicker" value="<?php echo set_value('db_dob', #$users->user_dob);?>" required>
</div>
</div>
<div class="row row_space">
<div class="col-md-5">
<label>Postal Code</label>
<input type="text" id="user_zip" name="user_zip" class="form-control" placeholder="00000" value="<?php echo set_value('xx_user_zip', #$users->user_zip);?>" required>
</div>
</div>
<input type="hidden" id="profile_old" name="profile_old" value="<?php $users->user_img; ?>">
<div class="row row_space">
<div class="col-md-5">
<button type="submit" name="" class="acct_btn" value="Update">Update Profile</button>
</div>
</div>
</form>
</div>
for upload new image to server with ajax, you need to use new FormData():
var fd = new FormData();
fd.append( 'user_zip', user_zip);
fd.append( 'xx_first_name', first_name);
fd.append( 'db_email', db_email);
fd.append( 'db_dob', datepicker);
fd.append( 'xx_last_name', last_name);
fd.append( 'user_img', $('#new_image')[0].files[0]);
$.ajax({
url: "<?php echo base_url('myaccount/profile/'.$this->session->userdata('id').''); ?>",
type: "post",
data: fd,
success: function () {
// do something
}
});

cannot input textarea with CKeditor on Codeigniter

when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter
My Controller
function AddNews(){
$data = array(
'title_news' => $this->input->post('title_news'),
'text' => $this->input->post('text_news'),
'date' => $this->input->post('date'),
);
$insert = $this->m_news->save($data);
echo json_encode(array("status" => TRUE));
}
My View
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_news"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<input name="title_news" placeholder="Title Name" class="form-control" type="text"><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<textarea class="ckeditor" name="text_news" rows="3" placeholder="Enter text . . . "></textarea><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date</label>
<div class="col-md-9">
<div class="input-group">
<input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" /><span class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></span>
</div>
</div>
</div>
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
</div>
</form>
My Ajax Input
function save()
{
var formData = new FormData($('#form')[0]);
$.ajax({
url : "<?php echo base_url('admin-spot/news/AddNews')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
redirect: true,
success: function(data){
if(data.status){
$('#modal_form').modal('hide');
}
else
{}
error: function (jqXHR, textStatus, errorThrown){
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
My Model
function Save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter
Add this to your script
function save()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var formData = new FormData($('#form')[0]);
$.ajax({
....
});
}

upload image using codeigniter with ajax and formdata

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 values are not insert to database , ajax response also not coming ,
can any one pls solve my issue.... Thanks in advance...
This is my view area.
<form action="<?php echo site_url("Admin_Creator/do_upload")?>" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="frm_imageuupload" method="post">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" id="selectsubmenu">
<option>--Select Sub Menu--</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="control-group form-group">
<div class="controls">
<label>Upload Photo:</label>
<input name="file" type="file" id="image_file" required>
<p class="help-block"></p>
</div>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
This is my Ajax coding
$('#submit').on('click',function(){
var inputFile=$('input[name=file]');
var fileToUpload=inputFile[0].files[0];
var other_data = $('#frm_imageuupload').serializeArray();
var formdata=new FormData();
formdata.append(fileToUpload);
formdata.append(other_data);
//now upload the file using ajax
$.ajax({
url:"<?php echo base_url('Admin_Creator/do_upload') ?>",
type:"post",
data:formdata,
processData:false,
contentType:false,
success: function(data){
if (data== 'true'){
window.location.reload();
}
else{
alert("Pls Try Again");
}
}
});
This is my controller Coding...
public function do_upload(){
$config['upload_path']="./upload";
$config['allowed_types']='gif|jpg|png';
$this->load->library('upload',$config);
if($this->upload->do_upload()){
$data = array('upload_data' => $this->upload->data());
$data1 = array(
'menu_id' => $this->input->post('selectmenuid'),
'submenu_id' => $this->input->post('selectsubmenu'),
'imagetitle' => $this->input->post('imagetitle'),
'imgpath' => $data['upload_data']['file_name']
);
$result= $this->Admin_model->save_imagepath($data1);
if ($result == TRUE) {
echo "true";
}
}
}
This is my model coding
public function save_imagepath($data1)
{
$this->db->insert('images', $data1);
return $this->db->insert_id();
}
Try This. It's working-
HTML Form-
<form enctype="multipart/form-data" id="submit">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" name="selectmenuid" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" name="selectsubmenu" id="selectsubmenu">
<option>--Select Sub Menu--</option>
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="control-group form-group">
<div class="controls">
<label>Upload Photo:</label>
<input name="file" type="file" id="image_file" required>
<p class="help-block"></p>
</div>
</div>
<button type="submit" class="btn btn-primary" id="sub">Submit</button>
</form>
Ajax -
$('#submit').submit(function(e){
e.preventDefault();
$.ajax({
url:'Your path',
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
alert(data);
}
});
});
Just set url in ajax, It would work perfectly.
Controller function-
public function do_upload(){
$config['upload_path']="./upload";
$config['allowed_types']='gif|jpg|png';
$this->load->library('upload',$config);
if($this->upload->do_upload("file")){
$data = array('upload_data' => $this->upload->data());
$data1 = array(
'menu_id' => $this->input->post('selectmenuid'),
'submenu_id' => $this->input->post('selectsubmenu'),
'imagetitle' => $this->input->post('imagetitle'),
'imgpath' => $data['upload_data']['file_name']
);
$result= $this->Admin_model->save_imagepath($data1);
if ($result == TRUE) {
echo "true";
}
}
}
this is simple.
problem is the ajax
you should stop the form submit first
$('form').on('submit',function(e){//bind event on form submit.
e.preventDefault();//stop submit
......... //your other codes
This what i did to solve that problem
HTML
<div class="form-group">
<label for="logo">Service Provider Logo / Icon</label>
<input type="file" class="form-control" name="file" id="file" required="required">
<img src="#" id="img-logo" alt="image" class="img-responsive" style="height: 200px !important;">
<input type="hidden" class="" id="returned-sp-id">
</div>
<div class="form-group">
<label for="caption">Service Provider Name</label>
<input type="text" class="form-control" id="caption" required="required">
</div>
<div class="form-group">
<label for="details">Service Provider Details</label>
<textarea type="text" class="form-control" id="details" required="required"></textarea>
</div>
</form>
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"] . "<br/><br/>";
} 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);
}
}
}
}
}

Categories