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>
Related
I am trying to make a crud small application to learn ajax, but I am facing serious problems here.
Here are some snippets, when I click on submit, the form doesn't do anything, just show me error 500 in chrome's console.And if I try to show something in success ajax function the request it's showing "undefined".
Thank you so much!
Here is my controller
public function store(Request $request)
{
$response = array(
'msg' => 'Thank you nephew'
);
$request->validate([
'name' => 'required|min:3',
'mobile' => 'required',
'address' => 'nullable',
'email' => 'nullable'
]);
$values = $request->all();
echo $values;
return Response::json($response);
}
Here is my Ajax script
<script>
$('#create-form').on('submit', function (event) {
event.preventDefault();
let name = $("input[name=name]").val();
let mobile = $("input[name=mobile]").val();
let email = $("input[name=email]").val();
let address = $("input[name=address]").val();
console.log(name);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$.ajax({
type: 'POST',
url: '{{ route('addresses.store') }}',
data: {name: name, mobile: mobile, email: email, address: address, token: $('input[name="_token"]').val()},
success: function (data) {
console.log(data);
}
});
});
</script>
Here is the blade modal
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="result"></div>
<form action="{{ route('addresses.store') }}" method="post" id="create-form">
#csrf
<div class="form-group">
<label for="">Name</label>
<input type="text" class="sequence-input" name="name"/>
</div>
<div class="form-group">
<label for="#">Mobile</label>
<input type="text" class="sequence-input" name="mobile"/>
</div>
<div class="form-group">
<label for="#">Address</label>
<textarea name="address" class="sequence-input" cols="30" rows="6"></textarea>
</div>
<div class="form-group">
<label for="#">Email Address</label>
<input type="text" class="sequence-input" name="email"/>
</div>
<div class="form-group">
<button type="submit" id="create" class="sequence-btn sequence-btn--primary">Create</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="sequence-btn sequence-btn--danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Try using single quotes on the name's value let mobile = $("input[name='mobile']").val(); and so on
Or
$.ajax({
type: 'POST',
url: '{{ route('addresses.store') }}',
data: $(this).serialize(),
success: function (data) {
console.log(data);
}
});
Your 500 error is caused by attempting to echo the array $values:
$values = $request->all();
echo $values; // <-- Your error is here.
Try using the dd helper method instead: dd($values)
My code displays an alert box in my popup form but I want to display the flash message in my popup form:
My Ajax:
$('#password_change_form').submit(function(e) {
e.preventDefault();
var saveThis = this;
$.ajax({
type: "POST",
url: "/changepassword",
data: $(saveThis).serialize(),
success: function(data) {
$('#password_change_form')[0].reset();
alert(data);
},
});
}),
My Controller:
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);
$obj_user->save();
$success_output = '<div class="alert alert-success">Password changed</div>';
} else {
$errors_output = '<div class="alert alert-danger">Wrong old password</div>';
$error = array(
'error' => $errors_output
);
echo json_encode($error);
}
$success = array(
'success' => $success_output
);
echo json_encode($success);
Here I want to show the success message in my popup form:
<div class="modal fade common_modal" id="change_password" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<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>
<h3>Změna hesla</h3>
</div>
<div class="modal-body">
<form role="form" id="password_change_form"
class="common_form_style popup_form">
<div class="row">
<div class="col-md-8 col-md-offset-2">
{{ csrf_field() }}
<span id="form_output"></span>
<div class="form-group">
<label for="password" style="width:100%">Původnà heslo </label>
<input id="password" type="password" class="form-control" name="password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<div class="form-group">
<label for="new_password" style="width:100%">NovÄ› heslo</label>
<input id="new_password" type="password" class="form-control" name="new_password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
<span class="help-block" style="color:#737373;font-size:14px;float:right;margin-right: 30px;font-weight: 100 !important;">MinimálnÄ› 8 znaků, jedno velké a malé pÃsmeno a ÄÃslo</span>
</div>
<div class="form-group">
<label for="heslo znovu">Potvrzenà heslo</label>
<input id="password_confirmation" type="password" class="form-control" name="password_confirmation">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<div class="submit-btn text-center">
<input type="submit"class="btn btn-default chci" value="Uložit" id="submit_form">
</div>
<div style="margin-top:10px;" id="success-messages"></div>
</div>
<div class="col-md-12 pull-right"></div>
</div>
</form>
I Want to display a success message but currently there is alert in my popup form. The alert screen shot:
Please change to this js code.
$(document).ready(function() {
$('#form').submit(function(e) {
e.preventDefault();
var saveThis = $(this);
$.ajax({
type: "POST",
url: "./index.php",
data: $(saveThis).serialize(),
success: function(data) {
var obj = $.parseJSON(data);
// I don't know where you want to show messages.
// In this case, outputting to id="form_output" element.
$('#form_output').html(obj.success);
}
});
});
});
I have a table which is being populated by book information using a while loop to fetch and display the results. The table consist of Book information and an Action Column which handles some functions like adding of quantity and deduction of quantity , etc..
Each button on the Action Column is using a modal to show the needed contents
like text boxes.
So my main problem right now is the contents of the modal only works on the first data of the table. I don't know if I'm missing something here or im doing it wrong. Any help would be great! (Im using ajax to insert data)
I can update this post if you need the php code on binding data on the table.
HTML code for the modal
<!-- ADD STOCK QUANTITY -->
<div class="modal fade" id="addqty<?php echo $bookisbn;?>" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content ">
<div class="modal-header">
<h3 style="text-align: center;">Add Stock/s
</h3>
</div>
<div class="modal-body">
<!-- <form role="form" id="add_stock_form" name="add_stock_form"> -->
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<label for="book_isbn1" class="form-label">Book ISBN
</label>
<input type="text" class="form-control text-center" id="book_isbn_as" name="book_isbn_as" value="<?php echo $bookisbn;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<input type="hidden" class="form-control" id="book_title_as" name="book_title_as" value="<?php echo $booktitle;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input type="number" class="form-control text-center" id="currentstock_as" name="currentstock_as" value="<?php echo $bookquantity;?>" readonly>
<label for="currentstock" class="form-label">Current Stock/s
</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input min="0" class="form-control text-center" type="text" id="book_quantity_as" name="book_quantity_as" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" required>
<label for="book_quantity_as" class="form-label">Enter Stock
</label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btn_add_stock" name="btn_add_stock" class="btn btn-success waves-effect">
<i class="material-icons">add
</i> ADD
</button>
<button type="button" class="btn btn-danger waves-effect" data-dismiss="modal">
<i class="material-icons">clear
</i> CLOSE
</button>
</div>
</div>
</div>
</div>
<!-- END OF ADD STOCK QUANTITY -->
Ajax Script
// //add quantity
$(document).on("click", "#btn_add_stock", function() {
var getbookisbn = $("#book_isbn_as").val();
var getbooktitle = $("#book_title_as").val();
var getbookquantity = $("#book_quantity_as").val();
var getcurrentquantity = $("#current_stock_as").val();
var whatprocess = "ADDBOOKQUANTITY";
if (validationaddquantity == 1) {
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: {
getbookisbn: getbookisbn,
getbooktitle: getbooktitle,
getbookquantity: getbookquantity,
whatprocess: whatprocess
},
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Quantity Added',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
/////REFRESH DATATABLE
$("#datatables").load(window.location + " #datatables");
$('#book_quantity_as').val("");
});
} else if (getdata == "ERROR") {
swal({
title: 'Sorry...',
text: "You cannot perform that action right now",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
fetch_data();
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).catch(swal.noop)
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
} else if (validationaddquantity != 1) {
swal({
title: 'Oops..!',
text: 'You must enter a value to proceed',
type: 'warning',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).catch(swal.noop)
}
});
on.show.bs.modal function trigger call you must re-assign value your row data (via ajax or get by td value on a table then post )to modal element input (i see is hidden input).
So every time call a modal your content data is shown based on click row table.
Maybe can solve ur problem..
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>
I'm having a problem to upload a file using bootstrap modal upload file
This is my modal code
<div id="myModalAtiv" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="alert alert-info" id="myModalLabel"><span class="glyphicon glyphicon-pencil"></span> Edição de Atividades</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="formacoes" enctype="multipart/form-data">
<div class="form-group">
<input type="hidden" name="idformacao" id="idformacao">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Escola:</label>
<input class="form-control" name="escola" id="escola" disabled="true">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Nome:</label>
<input class="form-control" name="nome" id="nome">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Data:</label>
<div class="input-group date" id="datetimePicker">
<input type="text" class="form-control" name="inicio" id="inicio" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Horas:</label>
<input class="form-control" name="horas" id="horas">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Local:</label>
<input class="form-control" name="local" id="local">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Destinatários:</label>
<input class="form-control" name="destinatarios" id="destinatarios">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Data Limite:</label>
<div class="input-group date" id="dataLimitePicker">
<input type="text" class="form-control" name="dataLimite" id="dataLimite" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span></div>
<span class="btn btn-file"><input type="file" name="fileToUpload" id="fileToUpload" /></span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info">Atualizar</button>
<button type="button" class="btn btn-default"data-dismiss="modal">Fechar</button>
</div>
</form>
</div>
</div><!-- End of Modal body -->
</div><!-- End of Modal content -->
and this is my ajax function to send the form
<script>
$(document).ready(function () {
$('#datetimePicker').datetimepicker({format: 'YYYY-MM-DD'});
$('#dataLimitePicker').datetimepicker({format: 'YYYY-MM-DD'});
$('#formacoes').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nome: {
validators: {
notEmpty: {
message: 'Tem de definir alguma formação'
}
}
}
},inicio: {
validators: {
notEmpty: {
message: 'Data inicial obrigatória'
},
date: {
format: 'YYYY-MM-DD',
message: 'Data inicial inválida'
}
}
},
dataLimite: {
validators: {
notEmpty: {
message: 'Data limite obrigatória'
},
date: {
format: 'YYYY-MM-DD',
message: 'Data limite inválida'
}
}
}
}).on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation');
$.ajax({
url: 'updates.php',
type: 'POST',
data: $form.serialize(),
success: function (response) {
console.log(response.status);
if (response.status === 'success') {
$("#myModalAtiv").modal('hide');
$('#respostas .modal-title').html('Sucesso');
$('#respostas .modal-body').html('Informação: ' + response.message);
$('#respostas').modal('show');
$('#respostas').on('hidden.bs.modal', function () {
window.location.reload(true);
});
}
}
});
});
});
All seems to be ok, but when i trying to send the from to my function it says
Notice: Undefined index: fileToUpload
This is my php function
$idformacao= filter_input(INPUT_POST, 'idformacao');
if ($idformacao != null) {
echo "aqui";
$userid = filter_input(INPUT_POST, 'userid');
$nome = filter_input(INPUT_POST, 'nome');
$inicio = filter_input(INPUT_POST, 'inicio');
$horas = filter_input(INPUT_POST, 'horas');
$local = filter_input(INPUT_POST, 'local');
$destinatarios = filter_input(INPUT_POST, 'destinatarios');
$dataLimite = filter_input(INPUT_POST, 'dataLimite');
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/uploads';
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$ret = $ebspma->updateFormacoes($idformacao, $nome, $inicio, $horas, $local, $destinatarios, $dataLimite,$target_path);
}
echo json_encode($ret);
}
And this is the line where i have the error
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);
e.preventDefault();
var fileToUpload= $('#fileToUpload')[0].files[0];
var idformacao = $("#idformacao").val();
var formData = new FormData(this);
formData.append('fileToUpload', fileToUpload);
formData.append('idformacao', idformacao);
//use this same format to append other of your fields
$.ajax({
type:'POST',
url: 'updates.php',
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(response){
//You can continue with your response status code here
}
Just hope that this works for you.
Add data-bs-focus="false" in modal first line at the end:
id="myModalAtiv" class="modal fade bs-example-modal-lg" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-bs-focus="false"