how to fix csrf in one page php ajax codeigniter problem - php

I'm using codeigniter 3 and I've got issue here, how to fix my code if i use CSRF. because I want only have one page action to view in codeigniter.
Here's my controller code :
public function index()
{
# code untuk menampilkan Database Rotator
$this->data['partial_head'] = '
<!-- DataTables -->
<link rel="stylesheet" href="'.base_url('assets').'/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="'.base_url('assets').'/plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
<link rel="stylesheet" href="'.base_url('assets').'/plugins/datatables-buttons/css/buttons.bootstrap4.min.css">';
$this->data['partial_body'] = '
<!-- DataTables & Plugins -->
<script src="'.base_url('assets').'/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="'.base_url('assets').'/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="'.base_url('assets').'/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="'.base_url('assets').'/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<!-- jquery-validation -->
<script src="'.base_url('assets').'/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="'.base_url('assets').'/plugins/jquery-validation/additional-methods.min.js"></script>
<!-- Custom JS -->
<script src="'.base_url('assets').'/dist/js/customJs/rotator-admin.js"></script>
';
$this->data['content'] = 'rotator/index';
$this->template->_render_page('layout/main',$this->data);
}
public function get_dataTable()
{
# code untuk menampilkan tabel ajax
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$query = $this->model->getAllData('rotator');
$data = [];
$no = 1;
foreach($query->result() as $row) {
$data[] = array(
$no++,
'+'.htmlentities($row->nomor_hp, ENT_QUOTES, "UTF-8"),
htmlentities($row->pesan, ENT_QUOTES, "UTF-8"),
htmlentities($row->jml_perulangan, ENT_QUOTES, "UTF-8").' kali',
($row->status_aktif==1)?
'<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input btn-aktif" name="aktif" id="'.encryptor('encrypt', $row->id_rotator).'" checked>
<label class="custom-control-label label-aktif" for="'.encryptor('encrypt', $row->id_rotator).'">Aktif</label>
</div>':'<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input btn-aktif" name="aktif" id="'.encryptor('encrypt', $row->id_rotator).'">
<label class="custom-control-label label-aktif" for="'.encryptor('encrypt', $row->id_rotator).'">Non Aktif</label>
</div>',
'<i class="fas fa-edit"></i>
<i class="fas fa-trash"></i>'
);
}
$result = array(
'draw' => $draw,
'recordsTotal' => $query->num_rows(),
'recordsFiltered' => $query->num_rows(),
'data' => $data
);
echo json_encode($result);
exit();
}
public function getByDataId($id = null)
{
# code untuk menampilkan Data Himpunan jika tombol edit di klik
$where = ['id_rotator' => encryptor('decrypt', $id)];
$hasil = $this->model->whereData($where, 'rotator')->row();
$data = [
'handphone' => $hasil->nomor_hp,
'pesan' => $hasil->pesan,
'isAktif' => $hasil->status_aktif,
'diulang' => $hasil->jml_perulangan,
'id' => $id
];
echo json_encode($data);
}
public function tambah_data()
{
# code untuk menambahkan data baru
$this->form_validation->set_rules('handphone', 'Nomor Handphone', 'trim|required|is_numeric|is_unique[rotator.nomor_hp]');
$this->form_validation->set_rules('pesan', 'Pesan', 'trim|required');
$this->form_validation->set_rules('diulang', 'Jumlah Perulangan', 'trim|required|is_numeric');
$this->form_validation->set_rules('isAktif', 'is Aktif', 'trim|numeric');
if ($this->form_validation->run() == FALSE) {
echo json_encode([
'alert_error' => validation_errors()
]);
} else {
$nomorHp = $this->input->post('handphone', true);
$pesan = $this->input->post('pesan', true);
$perulangan = $this->input->post('diulang', true);
$isAktif = !empty($this->input->post('isAktif', true)) ? 1 : 0;
$data = [
'nomor_hp' => $nomorHp,
'pesan' => $pesan,
'status_aktif' => $isAktif,
'jml_perulangan' => $perulangan,
];
if ($this->model->insertData($data, 'rotator')) {
echo json_encode([
'alert_success' => 'Data berhasil ditambahkan!',
'status' => TRUE
]);
} else {
echo json_encode([
'alert_success' => 'Data gagal ditambahkan!',
'status' => FALSE
]);
}
}
}
public function edit_data()
{
# code untuk mengubah Data
$this->form_validation->set_rules('handphone', 'Nomor Handphone', 'trim|required|is_numeric');
$this->form_validation->set_rules('pesan', 'Pesan', 'trim|required');
$this->form_validation->set_rules('diulang', 'Jumlah Perulangan', 'trim|required|is_numeric');
$this->form_validation->set_rules('isAktif', 'is Aktif', 'trim|numeric');
if ($this->form_validation->run() == FALSE) {
echo json_encode([
'alert_error' => validation_errors()
]);
} else {
$nomorHp = $this->input->post('handphone', true);
$pesan = $this->input->post('pesan', true);
$perulangan = $this->input->post('diulang', true);
$isAktif = !empty($this->input->post('isAktif', true)) ? 1 : 0;
$data = [
'nomor_hp' => $nomorHp,
'pesan' => $pesan,
'status_aktif' => $isAktif,
'jml_perulangan' => $perulangan,
];
$id = $this->input->post('idRotator', true);
if($this->model->updateData(['id_rotator' => encryptor('decrypt', $id) ], $data, 'rotator')){
echo json_encode([
'alert_success' => 'Data berhasil diubah!',
'status' => TRUE
]);
} else {
echo json_encode([
'alert_error' => 'Data Gagal diubah!',
'status' => FALSE
]);
}
}
}
public function hapus_data($id = null)
{
# code untuk menghapus Data Himpunan
$where = ['id_rotator' => encryptor('decrypt', $id)];
$this->model->deleteData($where, 'rotator');
echo json_encode([
'status' => TRUE
]);
}
public function aktif_handphone($id = null)
{
# code untuk mengaktifkan handphone
$this->form_validation->set_rules('aktif', 'Aktif Handphone', 'trim|is_numeric');
if ($this->form_validation->run() == FALSE) {
echo json_encode([
'alert_error' => validation_errors()
]);
} else {
$data = [
'status_aktif' => $this->input->post('aktif',true)
];
if($this->model->updateData(['id_rotator' => encryptor('decrypt', $id)], $data, 'rotator')){
echo json_encode([
'alert_success' => 'Data berhasil diubah!',
'status' => TRUE
]);
}
}
}
Here's my table in view code:
<table class="table table-bordered table-sm table-striped table-hover" id="dataTable"
width="100%" cellspacing="0">
<thead>
<tr>
<th>No.</th>
<th>Nomor HP</th>
<th>Pesan</th>
<th>Jumlah Diulang</th>
<th>Status</th>
<th width="12%">#</th>
</tr>
</thead>
</table>
Here's my modal in view code:
<!-- modal -->
<div class="modal fade" id="exampleModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
<button type="button" class="close btn-tutup" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form class="form-horizontal" action="" id="myForm" method="post" accept-charset="utf-8">
<div class="modal-body">
<div class="form-group row">
<label for="handphone" class="col-sm-4 col-form-label">Nomor Hp</label>
<div class="col-sm-8 inputan">
<input id="handphone" name="handphone" type="text" pattern="\d*" maxlength="13"
onkeypress="return isNumber(event)" class="form-control">
</div>
</div>
<div class="form-group row">
<label for="pesan" class="col-sm-4 col-form-label">Pesan Untuk Admin</label>
<div class="col-sm-8 inputan">
<textarea name="pesan" id="pesan" cols="30" rows="3" class="form-control"
style="resize: none;" maxlength="256"></textarea>
</div>
</div>
<div class="form-group row">
<label for="diulang" class="col-sm-4 col-form-label">Diulang Sebanyak</label>
<div class="col-sm-4 inputan">
<input id="diulang" name="diulang" type="text" pattern="\d*" maxlength="2" minlength="1"
min="1" max="10" onkeypress="return isNumber(event)" class="form-control">
</div>
<span class="col-sm-4 col-form-label">(x) kali</span>
</div>
<div class="form-group row">
<div class="col-4"></div>
<div class="col-8 inputan">
<div class="custom-control custom-checkbox custom-control-inline">
<input name="isAktif" id="checkbox_0" type="checkbox" class="custom-control-input"
value="1" required="required">
<label for="checkbox_0" class="custom-control-label">is Aktif</label>
</div>
</div>
</div>
<input id="idRotator" name="idRotator" type="hidden">
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default btn-tutup" data-dismiss="modal">Tutup</button>
<button type="submit" class="btn btn-primary">Simpan</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
and here's my script code:
//tampilkan data di datatables
$(document).ready(function() {
resetForm()
table = $('#dataTable').DataTable({
"ajax": {
url: 'rotator/get-dataTable',
type: 'POST'
},
})
})
$(function () {
// validasi form sebelum di kirim
$('#myForm').validate({
rules: {
handphone: {
required: true,
},
pesan: {
required: true,
},
diulang: {
required: true,
min: 1,
max: 10
},
isAktif: {
required: false
}
},
messages: {
handphone: {
required: "Pastikan masukan nomor telp dengan kode negara, misal 62xxxxxxxxxxx"
},
pesan: {
required: "Inputan pesan tidak boleh kosong!"
},
diulang: {
required: "Input angka 1 sampai 10",
min: "Input angka minimal 1",
max: "Input angka maksimal 10"
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.inputan').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
// jika form di submit
submitHandler: function() {
var data = $('#myForm').serialize()
$('.btn-simpan').text('simpan...') //ganti text button
$('.btn-simpan').attr('disabled', true) //set button disable
var url
if (save_method == 'add') {
url = "rotator/tambah-data"
} else {
url = "rotator/edit-data"
}
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'JSON',
success: function(data) {
if (data.status) {
toastr.success(data.alert_success)
$('#exampleModal').modal('hide')
reload_table()
resetForm()
} else {
var messages = data.alert_error.split("\n")
for(var i=0; i<messages.length - 1; i++)
toastr.error(messages[i])
}
$('.btn-simpan').text('Simpan') //ganti text button
$('.btn-simpan').attr('disabled', false) //set button enable
},
error: function(jqXHR, textStatus, errorThrown) {
toastr.error('Error ' + save_method + ' data')
$('.btn-simpan').text('Simpan') //ganti text button
$('.btn-simpan').attr('disabled', false) //set button enable
}
})
}
})
})
//fungsi jika tombol tutup di klik
$('.btn-tutup').on("click", function(e) {
e.preventDefault()
resetForm()
})
//fungsi jika tombol tambah di klik
$('.btn-tambah').on('click',function (e) {
e.preventDefault()
$('.modal-title').text('Tambah Data')
resetForm()
save_method = 'add'
})
//fungsi jika tombol edit di klik
$('#dataTable').on('click', '.btn-edit', function() {
$('.modal-title').text('Edit Data')
var url = "rotator/getByDataId/"
var id = this.id
save_method = 'update'
resetForm()
$.ajax({
url: url + id,
type: 'POST',
dataType: 'JSON',
success: function(data) {
$.each(data, function() {
$('[name="handphone"]').val(data.handphone)
$('[name="pesan"]').text(data.pesan)
$('[name="diulang"]').val(data.diulang)
if(data.isAktif>0){
$('input[name=isAktif]').attr('checked', 'checked')
} else {
$('input[name=isAktif]').removeAttr('checked')
}
$('[name="idRotator"]').val(data.id)
$('[name="idRotator"]').attr('readonly', true)
//console.log(data)
})
},
error: function(jqXHR, textStatus, errorThrown) {
//toastr.error('Gagal baca data dari ajax')
return false
}
})
})
//fungsi jika tombol hapus di klik
$('#dataTable').on('click', '.btn-hapus', function() {
var url = "rotator/hapus-data/"
var id = this.id
Swal.fire({
title: 'Yakin akan menghapus data?',
icon: 'question',
showDenyButton: true,
showCancelButton: false,
confirmButtonText: `Ya, Hapus`,
denyButtonText: `Tidak`,
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: url + id,
type: 'POST',
dataType: 'JSON',
success: function(data) {
Swal.fire('Dihapus!', 'data berhasil dihapus.', 'success')
reload_table()
resetForm()
},
error: function(xhr, ajaxOptions, thrownError) {
Swal.fire('Hapus Gagal!', 'Coba lagi', 'error')
}
})
} else if (result.isDenied) {
Swal.fire('Aman..!', 'Data tidak jadi dihapus.', 'info')
}
})
})
//fungsi untuk aktivasi handphone
$('#dataTable').on('click', '.btn-aktif', function() {
var url = "rotator/aktif-handphone/"
var id = this.id
var aktif = $('input#'+ id +':checked').val() ? '1' : '0'
$.ajax({
url: url + id,
type: 'POST',
dataType: 'JSON',
data : {aktif:aktif},
success: function(data) {
toastr.success(data.alert_success)
reload_table()
},
error: function(xhr, ajaxOptions, thrownError) {
toastr.error(data.alert_error)
return false
}
})
})
//fungsi untuk reload dataTabel
function reload_table() {
table.ajax.reload(null, false)
}
//fungsi untuk cek hanya angka yang diinput
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false
}
return true
}
//fungsi untuk reset form
function resetForm() {
$('#myForm').find('input:checkbox').removeAttr('checked') //kosongkan chekbox
$('#myForm').find('input:text').val('') //kosongkan form input
$('#myForm').find('textarea').text('') //kosongkan text area
}
if I try to setting my $config['csrf_protection'] = TRUE; will be error and showing notification, Where location we must locate <?= $this->security->get_csrf_token_name(); ?> and <?php echo $this->security->get_csrf_hash(); ?> to fix all ajax using csrf in one page..?

i come across this issue and if are you use multi form see this answer
https://stackoverflow.com/a/69407364/6559546

Related

How do I get errors which are handled serverside in a ajax error message after submitting a form?

The question
I have these files:
upload.php -> has the form and ajax
uploadSubmit.php -> sends the data to video.class.php
video.class.php -> handles the upload, adds it to the database and handles errors
How do I get the errors which are in else statements to transfer back to upload.php and be displayed in a div without the form the page refreshing?
The code:
upload.php
<script type="text/javascript">
$(document).ready(function() {
$('#uploadForm').submit(function(e) {
if($('#video').val()) {
e.preventDefault();
$(this).ajaxSubmit({
target: '#progress-div',
beforeSubmit: function() {
$("#progress-bar").width('0%');
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").attr('aria-valuenow', percentComplete).css('width', percentComplete + '%');
$("#progress-bar").text(percentComplete + '%');
},
success:function (){
$.ajax({
type: "GET",
url: "getvideourl.php",
dataType: "html",
success: function(response){
$("#responsecontainer").html(response);
$("#result").html('Your video was succesfuly uploaded.' + response);
$("#result").addClass("alert alert-success");
},
error:function (){
$("#responsecontainer").html(response);
$("#result").html('Something went wrong with the upload.');
$("#result").addClass("alert alert-alert");
},
});
},
error:function (){
$("#responsecontainer").html(response);
$("#result").html('Something went wrong with the upload.');
$("#result").addClass("alert alert-alert");
},
resetForm: true
});
return false;
}
});
});
</script>
<div id="result"></div>
<form id="uploadForm" action="uploadSubmit.php" enctype="multipart/form-data" method="POST">
<div class="input-group margin-bottom-sm" style="margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-camera-video-fill"></i></i> Select video</span>
<input class="form-control" id="video" type="file" name="video" accept="video/*" placeholder="Video" required/>
</div>
<div class="progress" id="progress-div" style="margin-bottom: 5px;">
<div class="progress-bar" id="progress-bar" role="progressbar" width="0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="input-group margin-bottom-sm" style="margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-camera-video-fill"></i></i> Select thumbnail</span>
<input class="form-control" id="thumbnail" type="file" name="thumbnail" accept="image/*" placeholder="Thumbnail" required/>
</div>
<div class="input-group margin-bottom-sm" style="margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-chat-right-text-fill"></i></i> Title</span>
<input class="form-control" type="text" name="title" placeholder="Title" required/>
</div>
<label for="description">Description:</label>
<textarea name="description" id="signature"></textarea>
<script>
$('#signature').summernote({
height: 250,
// toolbar
toolbar: [
['font', ['bold', 'italic', 'underline', 'clear']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['view', ['fullscreen']],
['help', ['help']]
]
});
</script>
<div class="input-group margin-bottom-sm" style="margin-top: 5px; margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-tags-fill"></i></i> Tags</span>
<input class="form-control" type="text" name="tags" placeholder="Separate by comma" />
</div>
<div><input type="submit" id="btnSubmit" value="Submit" class="btnSubmit" /></div>
</form>
uploadsubmit.php
<?php
include'config.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_FILES) && !empty($_FILES)){
$title = $_POST['title'];
$desc = $_POST['description'];
$tags = $_POST['tags'];
echo $video->upload($_FILES, $title, $desc, $tags);
}
else{
echo $toobig;
}
}
else{
die('<img src="https://i.kym-cdn.com/entries/icons/original/000/028/021/work.jpg" />');
}
?>
video.class.php
<?php
//Upload handler
public function upload($file, $title, $desc, $tags){
global $coreLang;
global $videoMessage;
$file = $_FILES['video'];
if(isset($_FILES['thumbnail'])){
$thumbnail = $_FILES['thumbnail'];
}
else{
$thumbnail = '';
}
if($file['error'] === 0){
$mimeType = mime_content_type($file['tmp_name']);
$fileType = explode('/', $mimeType)[0];
if(is_uploaded_file($file['tmp_name'])){
if ($fileType === 'video'){
$sourcePath = $file['tmp_name'];
$filename = $this->rand->String() . uniqid();
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$targetPath = "videos/users/" . $filename;
if(move_uploaded_file($sourcePath, $targetPath . '.' . pathinfo($file['name'], PATHINFO_EXTENSION))){
$query = $this->handler->prepare('INSERT INTO videos (u_id, v_filename, v_extension, v_title, v_desc, v_tags) VALUES (:u_id, :v_filename, :v_extension, :v_title, :v_desc, :v_tags)');
try{
$query->execute([
':u_id' => $this->user->getUserId(),
':v_filename' => $filename,
':v_extension' => $extension,
':v_title' => $title,
':v_desc' => $desc,
':v_tags' => $tags,
]);
}catch(PDOException $e){
return $this->errorHandler->dbError();
}
if(!empty($thumbnail)){
$this->uploadThumbnail($thumbnail, $filename);
}
}
else{
return $coreLang['error'];
}
}
else{
$videoMessage['noVideo'];
}
}
else{
return $coreLang['error'];
}
}
elseif($file['error'] === 1){
return $videoMessage['tooBig'];
}
elseif($file['error'] === 4){
return $videoMessage['noFile'];
}
elseif($file['error'] === 7){
return $videoMessage['diskError'];
}
else{
return $coreLang['error'];
}
}
?>
I managed to figure it out mostly by changing the Javascript to this:
<script type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: "uploadSubmit.php",
type: 'POST',
data: formData,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('#status').html('<b> Uploading -> ' + (Math.round(percentComplete * 100)) + '% </b>');
$("#progress-bar").width(Math.round(percentComplete * 100) + '%');
$("#progress-bar").attr('aria-valuenow', Math.round(percentComplete * 100)).css('width', Math.round(percentComplete * 100) + '%');
$("#progress-bar").text(Math.round(percentComplete * 100) + '%');
}
}, false);
return xhr;
},
success: function(data) {
if (data.includes('!=[]_')) {
$("#result").html(data.substr(5));
$("#result").addClass("alert alert-success");
}
else {
$("#result").html(data);
$("#result").addClass("alert alert-danger");
}
},
error: function(data){
},
cache: false,
contentType: false,
processData: false,
resetForm: true
});
return false;
});
});
</script>
After that I changed all return in the class to an echo and it worked.

Validation in AJAX Form Codeigniter

I've made a form in Ci which submits the data to the Db. I've been trying to implement validation in the form, For eg Name : more than 3+ Letters, email '#' Etc.
I never could seem to make it work, tried using Jquery validation with different sources , the form basically submits without Validation, Any pointers to where i'm going wrong?
The code below is just a snippet without any validation codes attached to it.
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "<?php echo $row_company->company_name; ?> "</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#click_form').click(function () {
var url = "<?php echo site_url('enquiry/ajax_post_form') ?>";
var data = $("#reg_form").serialize();
$.post(url, data, function (data) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}, "json");
});
});
</script>
</div>
</div>
</div>
</div>
Controller
public function ajax_post_form() {
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags');
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['message'] = 'Data Inserted Successfully';
echo json_encode($user_data);
}
Model
function form_insert($user_data){
$this->db->insert('pp_enquiry', $user_data);
}
**Validation **
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var email = document.getElementById("email1").value;
var mobile = document.getElementById("mobile").value;
//Check input Fields Should not be blanks.
if (name == '' || email == '' || mobile == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var email1 = document.getElementById("email");
var mobile = document.getElementById("mobile");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Must be 3+ letters' || email1.innerHTML == 'Invalid email' || mobile.innerHTML == 'Invalid website') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
Please check here is the working example of your above code. I think you missed something in your code.
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = 'https://www.example.com';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
console.log(data);
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "Company Name"</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
</div>
</div>
</div>
</div>
You need to run the validation process as explained in the manual: https://www.codeigniter.com/user_guide/libraries/form_validation.html#the-controller
if ($this->form_validation->run() == FALSE)
You can find below mentioned solution.
PHP Validation
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags|valid_email|min_length[3]');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags|min_length[10]|max_length[12]');
if ($this->form_validation->run() == FALSE) {
$data['status'] = false;
$data['error'] = validation_errors();
} else {
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['status'] = true;
$data['message'] = 'Data Inserted Successfully';
}
echo json_encode($data);
jQuery Validation
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = '<?php echo site_url('enquiry/ajax_post_form') ?>';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
// Code if required before Send
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
Let me know if it not works.

Edit the Logged In Profile with Ajax

I'm new to CodeIgniter and need some help :).
I managed to build a CRUD functions with ajax over some tutorials and I can Edit, Add new, Delete all user shown on my page. What I want now is when i Login with a user I just want the Logged in Profile to be Edited, not others. Please if someone can help me how can I manage to do that. Thank You in Advance.
Employee.php Controller
<?php
defined('BASEPATH') OR exit('No direct sripct access allowed');
Class Employee extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Employee_m', 'm');
}
function index()
{
$this->load->view('employee/index');
}
public function showAllEmployee()
{
$result = $this->m->showAllEmployee();
echo json_encode($result);
}
public function add_user()
{
$result = $this->m->add_user();
$msg['success'] = false;
$msg['type'] = 'add';
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
public function edit_user()
{
$result = $this->m->edit_user();
echo json_encode($result);
}
public function update_user()
{
$result = $this->m->update_user();
$msg['success'] = false;
$msg['type'] = 'update';
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
public function delete_user()
{
$result = $this->m->delete_user();
$msg['success'] = false;
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
Employee_m Model
<?php defined('BASEPATH') OR exit('No direct sripct access allowed');
class Employee_m extends CI_Model
{
public function showAllEmployee()
{
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return $query->result();
}
else
{
return false;
}
}
public function add_user()
{
$field = array(
'firstname' => $this->input->post('txtFirstName'),
'lastname' => $this->input->post('txtLastName'),
'username' => $this->input->post('txtUsername'),
'user_email' => $this->input->post('txtUserEmail'),
'user_password' => $this->input->post('txtUserPassword')
);
$this->db->insert('users',$field);
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function get_id(){
$id = $this->input->get('id');
$this->db->where('id',$id);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return $query->result();
}
else
{
return false;
}
}
public function update_user()
{
$id = $this->input->post('txtId');
$field = array(
'firstname' => $this->input->post('txtFirstName'),
'lastname' => $this->input->post('txtLastName'),
'username' => $this->input->post('txtUsername'),
'user_email' => $this->input->post('txtUserEmail'),
'user_password' => $this->input->post('txtUserPassword')
);
$this->db->where('id',$id);
$this->db->update('users',$field);
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
function delete_user()
{
$id = $this->input->get('id');
$this->db->where('id',$id);
$this->db->delete('users');
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
}
Index View
<?php $this->load->view('components/page_head'); ?>
<?php
if (isset($this->session->userdata['logged_in'])) {
$username = ($this->session->userdata['logged_in']['username']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: user_authentication");
}
?>
<div class="col-sm-9">
<div class="alert alert-success" style="display: none;">
</div>
<button id="btnAdd" class="btn btn-success">Add New</button>
<table class="table table-bordered table-responsive" style="margin-top: 20px;">
<thead>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Username</td>
<td>e-Mail</td>
<td>Actions</td>
</tr>
</thead>
<tbody id="showdata">
</tbody>
</table>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" 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>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal">
<input type="hidden" name="txtId" value="0">
<div class="form-group">
<label class="label-control col-md-4">First Name</label>
<div class="col-md-6">
<input type="text" name="txtFirstName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Last Name</label>
<div class="col-md-6">
<input type="text" name="txtLastName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Username</label>
<div class="col-md-6">
<input type="text" name="txtUsername" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">e-Mail</label>
<div class="col-md-6">
<input type="email" name="txtUserEmail" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Password</label>
<div class="col-md-6">
<input type="password" name="txtUserPassword" class="form-control" placeholder="******">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" 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>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body">
Do you want to delete this record?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnDelete" class="btn btn-danger">Delete</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
$(function () {
showAllEmployee();
// Add New
$('#btnAdd').click(function () {
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Add new user');
$('#myForm').attr('action','<?php echo base_url() ?>employee/add_user');
});
$('#btnSave').click(function () {
// alert('test');
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// validate the form
var firstname = $('input[name=txtFirstName]');
var lastname = $('input[name=txtLastName]');
var username = $('input[name=txtUsername]');
var user_email = $('input[name=txtUserEmail]');
var user_password = $('input[name=txtUserPassword]');
var result = '';
if (firstname.val()==''){
firstname.parent().parent().addClass('has-error');
}else {
firstname.parent().parent().removeClass('has-error');
result +='1';
}
if (lastname.val()==''){
lastname.parent().parent().addClass('has-error');
}else {
lastname.parent().parent().removeClass('has-error');
result +='2';
}
if (username.val()==''){
username.parent().parent().addClass('has-error');
}else {
username.parent().parent().removeClass('has-error');
result +='3';
}
if (user_email.val()==''){
user_email.parent().parent().addClass('has-error');
}else {
user_email.parent().parent().removeClass('has-error');
result +='4';
}
if (user_password.val()==''){
user_password.parent().parent().addClass('has-error');
}else {
user_password.parent().parent().removeClass('has-error');
result +='5';
}
if(result == '12345'){
$.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 = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('User '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function () {
alert('Could not add Data ');
}
});
}
});
//edit
$('#showdata').on('click', '.item-edit', function() {
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('edit user');
$('#myForm').attr('action','<?php echo base_url() ?>employee/update_user');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>employee/edit_user',
data: {id: id},
async: false,
dataType: 'json',
success: function(data) {
$('input[name=txtFirstName]').val(data.firstname);
$('input[name=txtLastName]').val(data.lastname);
$('input[name=txtUsername]').val(data.username);
$('input[name=txtUserEmail]').val(data.user_email);
$('input[name=txtUserPassword]').val(data.user_password);
$('input[name=txtId]').val(data.id);
},
error: function() {
alert('Could not Edit Data');
}
});
});
//delete
$('#showdata').on('click', '.item-delete', function () {
var id = $(this).attr('data');
$('#deleteModal').modal('show');
$('#btnDelete').unbind().click(function () {
$.ajax({
type: 'ajax',
method: 'get',
async: false,
url: '<?php echo base_url() ?>employee/delete_user',
data: {id: id},
dataType: 'json',
success: function (response) {
if(response.success){
$('#deleteModal').modal('hide');
$('.alert-success').html('User deleted successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function () {
alert('Error deleting');
}
});
});
});
//function
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>employee/showAllEmployee',
async: false,
dataType: 'json',
success: function (data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>'+data[i].id+'</td>'+
'<td>' + data[i].firstname + '</td>' +
'<td>' + data[i].lastname + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].user_email + '</td>' +
'<td>' +
'Edit' +
'Delete' +
'</td>' +
'</tr>';
}
$('#showdata').html(html);
},
error: function () {
alert('Could not get Data from Database');
}
});
}
});
</script>
</div>
<div class="col-sm-3">
<?php
echo "Hello <b id='welcome'><i>" . $username . "</i> !</b>";
echo "<br/>";
echo "Your ID is " . $id;
echo "<br/>";
?>
Logout
</div>
<?php $this->load->view('components/page_tail'); ?>
You need to fetch that user details to index page to avoid edting for other or need to set some condition such as passing users id on edit check if it same as edit id and then proceed for edit opertaion or else return some message

Codeigniter Form Validation Doesn't Work and display Error

I have used jQuery datatable for my project.when i add the form validation it display error called "the page at localhost says Error adding/update data. when i run the code without form validations it works fine.i couldn't understand what is the issue with my code.
Controller
class User_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('user_model','user_controller');
$this->load->library('form_validation');
}
public function index()
{
$this->load->helper('url');
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_view');
}
public function ajax_list()
{
$list = $this->user_controller->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->firstname;
$row[] = $person->lastname;
$row[] = $person->gender;
$row[] = $person->address;
$row[] = $person->contact_no;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" title="Edit" onclick="edit_person('."'".$person->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void()" title="Hapus" onclick="delete_person('."'".$person->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->user_controller->count_all(),
"recordsFiltered" => $this->user_controller->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->user_controller->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}
else{
$data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$insert = $this->user_controller->save($data);
echo json_encode(array("status" => TRUE));
}
}
public function ajax_update()
{
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}else{
$data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('contact_no'),
);
$this->user_controller->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
}
public function ajax_delete($id)
{
$this->user_controller->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
}
model
class User_model extends CI_Model {
var $table = 'user';
var $column = array('firstname','lastname','gender','address','contact_no');
var $order = array('id' => 'desc');
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column as $item)
{
if($_POST['search']['value'])
($i===0) ? $this->db->like($item, $_POST['search']['value']) : $this->db->or_like($item, $_POST['search']['value']);
$column[$i] = $item;
$i++;
}
if(isset($_POST['order']))
{
$this->db->order_by($column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
view
<h3>Client Data</h3>
<br />
<button class="btn btn-success" onclick="add_person()"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
<br />
<br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Address</th>
<th>Contact No</th>
<th style="width:125px;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Address</th>
<th>Date of Birth</th>
<th>Contact No</th>
</tr>
</tfoot>
</table>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
<script src="<?php echo base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
<script src="<?php echo base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('user_controller/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_person(id)
{
alert(id);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('user_controller/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="firstname"]').val(data.firstname);
$('[name="lastname"]').val(data.lastname);
$('[name="gender"]').val(data.gender);
$('[name="address"]').val(data.address);
$('[name="contact_no"]').val(data.contact_no);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('user_controller/ajax_add')?>";
}
else
{
url = "<?php echo site_url('user_controller/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function delete_person(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('user_controller/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
</script>
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<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 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstname" placeholder="First Name" class="form-control" type="text" >
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input name="lastname" placeholder="Last Name" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address"class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control" type="text">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
i would prefer HTML 5 validation because its very easy way and HTML 5 validation will check on client side or it will check without refresh the page and codeigniter form validation will refresh the page then show then show error so its a long way...so please use HTML 5 validation

How To insert data in mysql database using ajax in codeigniter?

I am trying to validate my form and insert the data in mysql database using ajax.Neither on submit validation is happening nor data is being inserted.I am making this in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
View :
<script type="text/javascript">
function validate_name(first_name){
if(first_name.trim() == '' || first_name.length == 0){
$('.first_name').show();
$('.first_name').text('Please enter your name');
return false;
} else {
$('.first_name').hide();
return true;
}
}
function validate_email(email_id){
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
if(email_id.trim() == '' || email_id.length == 0){
$('.email-id').show();
$('.email-id').text('Please enter email address');
return false;
}else if(!pattern.test(email_id)) {
$('.email-id').show();
$('.email-id').text('Please enter valid email address');
return false;
} else {
$('.email-id').hide();
return true;
}
}
function validate_inquiry_form(first_name,email_id){
var username_validate = validate_name(first_name);
var email_validate = validate_email(email_id);
if(username_validate == true && email_validate == true){
return true;
} else {
return false;
}
}
$('#submit_enquiry').click(function(){
var first_name = $("input[name=first_name]").val();
var last_name = $("input[name=last_name]").val();
var dob = $("input[name=dob]").val();
var gender = $("input[name=gender] :radio:checked").val();
var email_id = $("input[name=email_id]").val();
var password = $("input[name=password]").val();
var address = $("input[name=address]").val();
var phone = $("input[name=phone]").val();
var zipcode = $("input[name=zipcode]").val();
var validate_form = validate_inquiry_form(first_name,email_id);
if(validate_form == true){
$.ajax({
url:'<?php echo base_url(); ?>member/register',
type:'POST',
data:{
first_name : first_name ,last_name : last_name ,dob : dob ,male : male ,female : female , email_id : email_id ,password : password ,phone : phone , address : address , zipcode : zipcode
},
success: function(data) {
console.log(data);
}
});
} else {
return false;
}
return false;
});
</script>
<form id="registration-form">
<div class="register">
<div class="row">
<div class="col1">
<label for="first_name">First Name<span>*</span></label> <br/>
<input type="text" name="first_name"/>
<li class="first_name error"></li>
</div>
<div class="col2">
Last Name<br/>
<input type="text" name="last_name"/>
</div>
</div>
<div class="row">
<div class="col1">
Date Of Birth <br/>
<input type="text" name="dob"/>
</div>
<div class="col2">
Gender
<br/>
<input type="radio" name="gender" value="Male" /> Male
<input type="radio" name="gender" value="Female" /> Female
</div>
</div>
<div class="row">
<div class="col1">
Email<br/>
<input type="text" name="email_id"/>
<li class="email-id error"></li>
</div>
<div class="col2">
Password<br/>
<input type="password" name="password"/>
</div>
</div>
<div class="row">
<div class="col">
Address<br/>
<textarea name="address" rows="2" ></textarea>
</div>
</div>
<div class="row">
<div class="col1">
Zipcode<br/>
<input type="text" name="zipcode"/>
</div>
<div class="col2">
Phone<br/>
<input type="text" name="phone"/>
</div>
</div>
<div class="row">
<div class="col3">
<input class="" type="button" id="submit_enquiry" name="submit_enquiry" value="Submit Enquiry" />
</div>
</div>
</div>
</form>
Controller:
public function register_user()
{
$register_user = $this->member_model->add_user();
if($register_user)
{
return true;
}
else
{
return false;
}
}
Model :
public function add_user()
{
$add_user = array(
'mem_name'=> $this->input->post('first_name'),
'mem_lastname'=> $this->input->post('last_name'),
'mem_dob'=> $this->input->post('dob'),
'mem_gender'=> $this->input->post('gender'),
'mem_email'=> $this->input->post('email_id'),
'mem_address'=> $this->input->post('address'),
'mem_zipcode'=> $this->input->post('zipcode'),
'mem_phone'=> $this->input->post('phone'),
'mem_password'=> $this->input->post('password'),
);
$insert = $this->db->insert('membership', $add_user);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Please help me ....
change in this in your ajax add apostrophe (')
data:{
'first_name' : first_name ,'last_name' : last_name ,'dob' : dob , etc...
},
add this in your controler member
function register(){
$add_user = array(
'mem_name'=> $this->input->post('first_name'),
'mem_lastname'=> $this->input->post('last_name'),
'mem_dob'=> $this->input->post('dob'),
'mem_gender'=> $this->input->post('gender'),
'mem_email'=> $this->input->post('email_id'),
'mem_address'=> $this->input->post('address'),
'mem_zipcode'=> $this->input->post('zipcode'),
'mem_phone'=> $this->input->post('phone'),
'mem_password'=> $this->input->post('password'),
);
$this->member_model->add_user($add_user);
}
in your member_model
function add_user($add_user){
$insert = $this->db->insert('membership', $add_user);
}
You can use jquery validate and use ajay on submit handler. Please try following code:
$(function () {
$("#FormId").validate({
errorElement: 'span', errorClass: 'help-block',
rules: {
Tag: {
required: true
},
Table: {
required: true
},
Field: {
required: true
},
},
messages: {
Tag: {
required: "Tag is required."
},
Table: {
required: "Table is required."
},
Field: {
required: "Field is required."
},
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').children('span.help-block').remove();
},
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group'));
},
submitHandler: function (form) {
$("#saveButton").button('loading');
$.post('', $("#FormId").serialize(), function (data) {
//Write your code here
});
}
});
});```

Categories