Error file Upload Codeigniter Ajax - php

Error loading file to server and check everything and apparently it's okay please help
enter image description here
View
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" name="txtProdId" value="0">
<div class="form-group">
<label for="category" class="label-control col-md-4">Nombre categoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtId" id="categoria">
</select>
</div>
</div>
<div class="form-group">
<label for="subcategory" class="label-control col-md-4">Nombre subcategoría</label>
<div class="col-md-8">
<select class="form-control col-md-4" for="name" name="txtSubId" id="subcategoria">
</select>
</div>
</div>
<div class="form-group">
<label for="codig" class="label-control col-md-4">Codigo</label>
<div class="col-md-8">
<input type="text" name="txtCodigo" class="form-control">
</div>
</div>
<div class="form-group">
<label for="name" class="label-control col-md-4">Nombre Producto</label>
<div class="col-md-8">
<input type="text" name="txtProducto" class="form-control">
</div>
</div>
<div class="form-group">
<label for="description" class="label-control col-md-4">Descripción</label>
<div class="col-md-8">
<textarea class="form-control" name="txtDescripcion"></textarea>
</div>
</div>
<div class="form-group">
<label for="picture" class="label-control col-md-4">Imagen</label>
<div class="col-md-8">
<input type="file" name="txtFoto" id="txtFoto">
</div>
</div>
<div class="form-group">
<label for="cant" class="label-control col-md-4">Cantidad</label>
<label for="catalog" class="label-control col-md-4">Precio catálogo</label>
<label for="ofert" class="label-control col-md-4">Precio oferta</label>
</div>
<div class="input-group">
<div>
<input type="text" name="txtCantidad" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtCatalogo" class="form-control">
</div>
<span class="input-group-addon">-</span>
<div>
<input type="text" name="txtOferta" class="form-control">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="button" id="btnSave" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
Jquery ajax View
$(function(){
showAllProduct();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Registrar Producto');
$('#myForm').attr('action', '<?php echo base_url() ?>producto/addProduct');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var codig = $('input[name=txtCodigo]');
var productName = $('input[name=txtProducto]');
var description = $('textarea[name=txtDescripcion]');
var cant = $('input[name=txtCantidad]');
var catalog = $('input[name=txtCatalogo]');
var ofert = $('input[name=txtOferta]');
var myFile = $("#txtFoto").val();
alert(myFile);
var result = '';
if(codig.val()==''){
codig.parent().parent().addClass('has-error');
}else{
codig.parent().parent().removeClass('has-error');
result +='1';
}
if(productName.val()==''){
productName.parent().parent().addClass('has-error');
}else{
productName.parent().parent().removeClass('has-error');
result +='2';
}
if(description.val()==''){
description.parent().parent().addClass('has-error');
}else{
description.parent().parent().removeClass('has-error');
result +='3';
}
if(cant.val()==''){
cant.parent().parent().addClass('has-error');
}else{
cant.parent().parent().removeClass('has-error');
result +='4';
}
if(catalog.val()==''){
catalog.parent().parent().addClass('has-error');
}else{
catalog.parent().parent().removeClass('has-error');
result +='5';
}
if(ofert.val()==''){
ofert.parent().parent().addClass('has-error');
}else{
ofert.parent().parent().removeClass('has-error');
result +='6';
}
//if()
if(result=='123456'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'añadido';
}else if(response.type=='update'){
var type ='actualizado';
}
$('.alert-success').html('Producto '+type+' con éxtito').fadeIn().delay(4000).fadeOut('slow');
showAllProduct();
}else{
alert('Error');
}
},
error: function(){
alert('No se puede añadir el dato');
}
});
}
});
});
Controller: The file 'txtFoto' does not arrive is as if it had been sent from the form
public function addProduct(){
$pathArchivo = $this->filePath();
$result = $this->m->addProduct($pathArchivo);
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function filePath(){
$archivo=$_FILES['txtFoto'];
$config['upload_path'] = realpath(APPPATH.'../image/product/');
//$config['file_name'] = "nombre_archivo";
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['max_size'] = "50000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
$res = '';
if ( ! $this->upload->do_upload($archivo)) {
$error = array('error' => $this->upload->display_errors());
$res = 'hola no funciona';
print_r($error);
}else {
$file_data = $this->upload->data();
$file_path = './image/product/'.$file_data['file_name'];
$res = $file_path;
//print_r($data);
}
return $res;
}
Model
public function addProduct($path){
$field = array(
'sub_id'=>$this->input->post('txtSubId'),
'pr_codigo'=>$this->input->post('txtCodigo'),
'pr_nombre'=>$this->input->post('txtProducto'),
'pr_descripcion'=>$this->input->post('txtDescripcion'),
'pr_cantidad_stock'=>$this->input->post('txtCantidad'),
'pr_precio_catalogo'=>$this->input->post('txtCatalogo'),
'pr_precio_oferta'=>$this->input->post('txtOferta'),
'pr_foto'=>$path
);
$this->db->insert('producto', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}

Your method is correct if you are trying to send a TEXT file.
Before you continue doing it with AJAX ,
Lets try and send the file normally
and you would want to receive it like this
$this->upload->do_upload('txtFoto');
I am just curious , If you are using ci's upload handler , why do you take it from PHP's $_FILE?
$_FILES['txtFoto']
Can you share any var_dump from $_FILES?
EDIT
You can do it via AJAX using FormData
var formData = new FormData($('#myForm'))
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
success: function(response){
//handle success
},
error: function(){
//handle error
alert('No se puede añadir el dato');
}
});
On the Controller ,
Initialize your upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
And make sure that the directory you want to upload your image is writable

Related

Insert multiple values in row php

I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.

Ajax file upload without formdata

when i try to upload a file, all data send to database but the input file is empty and won't upload the file how can i send file with my
actual ajax submit form ? without dataForm i'm new to ajax and mysql
here's my code:
function getUsers(){
$.ajax({
type: 'POST',
url: 'tpl/add.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
function userAction(type,idb){
id = (typeof idb == "undefined")?'':idb;
var statusArr = {add:"ajouter",edit:"mises à jour",delete:"supprimer"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&idb='+idb;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else if (type == 'view'){
userData = $("#viewForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&idb='+idb;
}
$.ajax({
url: 'tpl/add.php',
cache: false,
data: userData,
type: 'POST',
contentType: false,
processData: false,
success:function(msg){
if(msg == 'ok'){
alert('Le model a été '+statusArr[type]+' avec succès.');
getUsers();
$('.form')[0].reset();
$('#myModal2').modal('hide');
$('#myModal').modal('hide');
}else{
alert('Un probleme à été detecter, veuillez reessayer.');
}
}
});
}
function editUser(idb){
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'tpl/add.php',
data: 'action_type=data&idb='+idb,
success:function(data){
$('#idbEdit').val(data.idb);
$('#modelEdit').val(data.model);
$('#urldemoEdit').val(data.urldemo);
$('#modelfichEdit').val(data.modelfich);
$('#etatEdit').val(data.etat);
$('#editForm').slideDown();
}
});
}
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ajouter un modele</h4>
</div>
<div class="modal-body" id="addForm">
<form class="form form-horizontal" method="post" id="userForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-3">Modele HTML</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="model" id="model"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Aperçu</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="urldemo" id="urldemo"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Fichier HTML </label>
<div class="col-sm-9">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Etat</label>
<div class="col-sm-9">
<select name="etat" id="etat" class="form-control">
<option value="0">activé</option>
<option value="1">désactivé</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
Ajouter
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
</div>
</form>
</div>
</div>
</div>

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
}
});

form validation code igniter doesn't work

i am a beginner in using form validation in codeigniter, now i am trying to use form validation codeigniter library, why this is not executed? i already loaded the $this->load->library('form_validation'); at the top of my controller. I mean i want the output where it puts error below my input type. Why my error in array('required' => 'Error Message on rule2 for this field_name')); doesnt appear in my view. Only in Response at console
Here is my fullcode:
VIEW:
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="frm_create_user">
<div class="form-group">
<label for="userFName" class="control-label col-sm-4">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userFName" id="userFName" placeholder="First name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
<div class="form-group">
<label for="userMName" class="control-label col-sm-4">Middle Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="userMName" id="userMName" placeholder="Middle name">
<div class="msg"></div><!-- form-group -->
</div><!-- col-sm-6 -->
</div><!-- form-group -->
</form><!-- form-horizontal -->
<button type="button" id="btn_reg" onclick="create_User()" class="btn btn-primary">Create Account</button>
i am just trying one input type and some error for validating, now here is my Controller code:
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == FALSE) {
$result['type'] = 'error';
$result['message'] = validation_errors();
}else {
$result['type'] = 'success';
$result['message'] = 'Whooos..! Your Succes Message';
}
echo json_encode($result);
}
my ajax from view:
function create_User() {
$.ajax({
url: siteurl+"admin_controls/reg_user",
type: "POST",
data: $("#frm_create_user").serialize(),
dataType: "JSON",
success: function(data) {
alert(" User Successfully Added added! ");
$("#frm_create_user")[0].reset();
}
});
}
Please follow this Method.
Or
If you just copy and paste this code it will definately work, all you need to just change the controller name in the form action
public function reg_user(){
$this->form_validation->set_rules('userFName', 'userFName', 'trim|required',
array('required' => 'Error Message on First name ')
);
$this->form_validation->set_rules('userMName', 'userMName', 'trim|required',
array('required' => 'Error Message on Middle Name')
);
if ($this->form_validation->run() == TRUE) {
$result['status'] = true;
$result['message'] = "Data inserted successfully.";
}else {
$result['status'] = false;
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Now the Ajax Part
In Ajax i am using the FormData function instead of using serialize function. In case if you are going to upload files it will be helpful.
<script type="text/javascript">
$(document).ready(function() {
$("#form_data").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_data"));
$.ajax({
url : $("#form_data").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
return false;
});
View Part
<a data-toggle="modal" href='#admin_create_acct' class="list_sort">Select<a>
<div class="modal fade large" id="admin_create_acct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header btn-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Create Account</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="<?php echo base_url('Practice/test_user')?>" method="post" id="form_data">
<div class="form-group">
username : <input type="text" class="form-control" name="name">
<span class="error userFName"></span>
</div>
<div class="form-group">
password : <input type="text" class="form-control" name="userMName">
<span class="error userMName"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
</div>
</div>
</div>
</div>

Image upload not working with event.preventDefault() CodeIgniter

I have created a form in CodeIgniter for uploading an image.
The View file:
<form method="POST" action="<?php echo base_url().'promotions/add_item' ?>" enctype='multipart/form-data' class="form-horizontal" id="addItem">
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="pro_image">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
</div>
</div>
</form>
The Ajax code:
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#addItem").serialize(),
type: $(this).attr('method')
}).done(function(data) {
$('#ret').html(data);
// window.location.reload();
$('#addItem')[0].reset();
});
event.preventDefault();
});
});
</script>
The Controller file:
<?php
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
var_dump($_FILES['pro_image']);
if ($this->form_validation->run() == FALSE) {
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
} else {
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('pro_image')) {
echo 'Error :'. $this->upload->display_errors();
}
$data = $this->upload->data();
$img = $data['file_name'];
}
$title = $this->input->post('title');
$description = $this->input->post('description');
$this->promotions_model->add_item($title, $description,'uploads/'.$img);
}
Whenever I attempt to upload an image it always comes as null, but if I comment out the event.preventDefault(); line then upload an image, then it works fine. However, then the other functionality like validation and return messages fail to work properly.
Can any one please tell me what is issue with event.preventDefault()?
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
event.preventDefault();
var url = $(this).attr('action');
var data= new FormData($("#addItem")[0]);
$.ajax({
url: url,
contentType:false,
cache:false,
processData:false,
data: data,
type: 'POST' // POST/GET
success:function(data) {
$('#ret').html(data);
$('#addItem')[0].reset();
}
});
});
});
Add event.preventDefault(); in the begining sumbit listner

Categories