Ajax datatable is not inserting - ajax

I am studying about ajax datatabl. My AJAX datatable insert is not working. It has no error on console or whatsoever. It's just whenever I am inserting, the datatable is just refreshing. Is there anything that I missed? I have provided my codes below. Any help will be appreciated. Thank you very much.
This is the result whenever i'm adding. But it's not adding on database or whatsoever.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="35%">Name</th>
<th width="35%">Email</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<!-- <input type="file" name="user_image" id="user_image" /> -->
<!-- <span id="user_uploaded_image"></span> -->
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 3],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
if(name != '' && email != '')
{
$.ajax({
url:"<?php echo base_url() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
console.log(name);
console.log(email);
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
});
</script>
Controller:
function fetch_user(){
$this->load->model("profiles");
$fetch_data = $this->profiles->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = $row->name;
$sub_array[] = $row->email;
$sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"] )),
"recordsTotal" => $this->profiles->get_all_data(),
"recordsFiltered" => $this->profiles->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post("email.")
);
$this->load->model('profiles');
$this->profiles->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profiles");
$data = $this->profiles->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['name'] = $row->name;
$output['email'] = $row->email;
}
echo json_encode($output);
}
}
Model:
var $table = "userss";
var $select_column = array("id", "name", "email");
var $order_column = array(null, "name", "email", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("name", $_POST["search"]["value"]);
$this->db->or_like("email", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('id', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if($_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud()
{
$this->db->insert('userss', $data);
}

What is your database structure? Is the table called userss or users?
$this->db->insert('userss', $data); <--Possible typo?
You likely will need to use the inspect feature of your browser and look at any responses under the network tab to see any errors.

Related

why my submit form not working on mobile phone?

I use laravel 9 and i have a registration form and submit button for some reason doesn't work in mobile phone only, but its working fine in desktop. Any idea what wrong? Thankyou!
Html (blade):
<form action="{{ route('jokibukti') }}" method="POST">
#csrf
<td width="25%">{{ $item->keterangan }} <input type="text"
id="ketbaru" name="keteranganbaru" class="form-control"
placeholder="Masukan Bonus Disini!"></td>
{{-- <td width="7%"><a class="btn btn-primary btn-sm" onclick=''>Selesai</a> --}}
<td width="25%">
<input type="hidden" name="id" value="{{ $item->id }}">
<label class="">
<span class="sr-only">Pilih Gambar</span>
<input type="file" name="image" class="" />
#error('image')
<span class="text-red-600 text-sm">{{ $message }}</span>
#enderror
</label>
<button type="submit" value="submit" class="btn btn-primary btn-sm">Submit</button>
</form>
Route :
Route::post('/joki/bukti', [ControllerJoki::class, 'buktiselesai'])->name('jokibukti');
Controller :
public function buktiselesai(Request $request)
{
// #dd($request->image);
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
$ketbaru = $request->keteranganbaru;
$ketlamauser = Jokiongoing::where('id', $request->id)->first();
$ketlama = $ketlamauser->keterangan;
if ($ketlama != "") {
$keterangan = $ketlama . " & " . $ketbaru;
} else {
$keterangan = $ketbaru;
}
// $image_path = $request->file('image')->store('buktijoki', 'public');
$imageName = time() . '.' . $request->image->extension();
$request->image->move(public_path('buktijoki'), $imageName);
$data = Jokiongoing::where('id', $request->id)->update([
'bukti' => $imageName,
'keterangan' => $keterangan,
'acc' => '1',
]);
if ($data) {
return redirect()->route('jokiaktif')->with(['success' => 'Bukti Berhasil disimpan']);
} else {
return redirect()->route('jokiaktif')->with(['error' => 'Bukti Gagal Disimpan']);
}
}
<script>
var tap = true;
document.addEventListener('touchstart', function(e) {
tap = true;
});
document.addEventListener('touchmove', function(e) {
tap = false;
});
document.addEventListener('touchend', function(e) {
if (tap) {
//users tapped the screen
}
});
</script>
Trying adding this script from someone in the stackoverflow, but get nothing as result.
Im try to add onClick to the button
<button onClick = "testsubmit()" value="submit" class="btn btn-primary btn-sm">Submit</button>
<script>
function testsubmit() {
alert("masuk");
}
</script>
and its work fine, what happen to type="submit" ?

I want to make fullcalendar with codeigniter,,but somehow I encounter this error

I encounter this error. Please help me if you know the solution
Severity: Error
Message: Call to undefined function form_open()
Filename: views/index.php
Line Number: 33
index.php (view)
Calendar Display
<script src="<?php echo base_url(); ?>assets/fullcalendar/lib/moment.min.js"></script>
<script src="<?php echo base_url(); ?>assets/fullcalendar/lib/jquery-ui.min.js"></script>
<script src="<?php echo base_url(); ?>assets/fullcalendar/lib/jquery.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/fullcalendar/fullcalendar.min.css" />
<script src="<?php echo base_url(); ?>assets/fullcalendar/fullcalendar.min.js"></script>
<script src="<?php echo base_url(); ?>assets/fullcalendar-3.9.0/locale/es.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Calendar</h1>
<div id="calendar">
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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" id="myModalLabel">Add Calendar Event</h4>
</div>
<div class="modal-body">
<?php echo form_open(site_url('calendar/add_event'), array("class" => "form-horizontal")) ?>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">Event Name</label>
<div class="col-md-8 ui-front">
<input type="text" class="form-control" name="name" value="">
</div>
</div>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">Description</label>
<div class="col-md-8 ui-front">
<input type="text" class="form-control" name="description">
</div>
</div>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">Start Date</label>
<div class="col-md-8">
<input type="text" class="form-control" name="start_date">
</div>
</div>
<div class="form-group">
<label for="p-in" class="col-md-4 label-heading">End Date</label>
<div class="col-md-8">
<input type="text" class="form-control" name="end_date">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Add Event">
<?php echo form_close() ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>-->
<script type="text/javascript">
$(document).ready(function() {
var date_last_clicked + null;
$('#calendar').fullCalendar({
eventSources: [
{
events: function(start, end, timezone, callback) {
$.ajax({
url: '<?php echo base_url() ?>calendar/get_events',
dataType: 'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(msg) {
var events = msg.events;
callback(events);
}
});
}
},
]
dayClick: function(date, jsEvent, view) {
date_last_clicked = $(this);
$(this).css('background-color', '#bed7f3');
$('#addModal').modal();
},
});
});
</script>
<style>
#calendar{
width: 800px;
margin: 0px auto;
}
</style>
</body>
Calendar.php (controller)
class Calendar extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model("calendar_model");
}
public function index()
{
$this->load->helper('url');
$this->load->view('index', array());
}
public function get_events()
{
// Our Start and End Dates
$start = $this->input->get('start');
$end = $this->input->get('end');
$startdt = new DateTime('now'); // setup a local datetime
$startdt->setTimestamp($start); // Set the date based on timestamp
$start_format = $startdt->format('Y-m-d H:i:s');
$enddt = new DateTime('now'); // setup a local datetime
$enddt->setTimestamp($end); // Set the date based on timestamp
$end_format = $enddt->format('Y-m-d H:i:s');
$events = $this->calendar_model->get_events($start_format, $end_format);
$data_events = array();
foreach($events->result() as $r) {
$data_events[] = array(
"id" => $r->ID,
"title" => $r->title,
"description" => $r->description,
"end" => $r->end,
"start" => $r->start
);
}
echo json_encode(array("events" => $data_events));
exit();
}
public function add_event()
{
/* Our calendar data */
$name = $this->input->post("name", TRUE);
$desc = $this->input->post("description", TRUE);
$start_date = $this->input->post("start_date", TRUE);
$end_date = $this->input->post("end_date", TRUE);
if(!empty($start_date)) {
$sd = DateTime::createFromFormat("Y/m/d H:i", $start_date);
$start_date = $sd->format('Y-m-d H:i:s');
$start_date_timestamp = $sd->getTimestamp();
} else {
$start_date = date("Y-m-d H:i:s", time());
$start_date_timestamp = time();
}
if(!empty($end_date)) {
$ed = DateTime::createFromFormat("Y/m/d H:i", $end_date);
$end_date = $ed->format('Y-m-d H:i:s');
$end_date_timestamp = $ed->getTimestamp();
} else {
$end_date = date("Y-m-d H:i:s", time());
$end_date_timestamp = time();
}
$this->calendar_model->add_event(array(
"title" => $name,
"description" => $desc,
"start" => $start_date,
"end" => $end_date
)
);
redirect(site_url("calendar"));
}
}
Calendar_model.php (model)
class Calendar_model extends CI_Model {
public function get_events($start, $end){
return $this->db->where("start >=", $start)->where("end <=", $end)->get('calendar_events');
}
public function add_event($data)
{
$this->db->insert('calendar_events', $data);
}
public function get_event($id)
{
return $this->db->where("ID", $id)->get('calendar_events');
}
public function update_event($id, $data)
{
$this->db->where("ID", $id)->update('calendar_events', $data);
}
public function delete_event($id)
{
$this->db->where("ID", $id)->delete('calendar_events');
}
}
From the HTML it seems there is a markup issue. But anyway you need to make sure that the Form helper and URL helpers are both loaded in the function you want to use.
public function index()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->view('index', array());
}

Ajax post request- Unresolvable dependency resolving and error 500

I'm trying to create a multi-step form using jQuery anad AJAX. But Im getting this error when "go to step 2" is clicked:
jquery.min.js:4 POST http://store.test/product/1/product-test/payment/storeUserInfo 500 (Internal Server Error)
Also when clicking in network tab and then click in "storeUserInfo" it appears:
exception
:
"Illuminate\Contracts\Container\BindingResolutionException"
file
:
"/Users/jakeB/projects/store/vendor/laravel/framework/src/Illuminate/Container/Container.php"
line
:
933
message
:
"Unresolvable dependency resolving [Parameter #1 [ <required> array $data ]] in class Illuminate\Validation\Validator"
Do you know where is the error?
In the PaymentController there is the storeUserInfo() Method that is the method for the step 1:
public function storeUserInfo(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
Route:
Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [
'uses' => 'PaymentController#storeUserInfo',
'as' =>'products.storeUserInfo'
]);
// step 1 and step 2 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" id="step1form" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input name="name" type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
<div class="tab-pane fade clearfix tabs hide" id="step2" role="tabpanel" aria-labelledby="profile-tab">
<form method="post">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="paymentmethod1" value="option1" checked>
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="credit_card" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Stripe</span>
</label>
</div>
</div>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<button type="button" data-nexttab="#step3" href="#step3"
class="btn btn-primary btn ml-2 next-step">
Go to step 3
</button>
</div>
</form>
</div>
// ajax in payment.blade.php
$('#goToStep2').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storeUserInfo',compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
}, 3000);
},
error: function (data) {
console.log(data);
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
$('#response').show().html(errorsHtml);
}
});
});
});
Use Validator facade class in your PaymentController
use Validator;
class PaymentController extends Controller
{
public function storeUserInfo(Request $request, $id, $slug = null){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
}

dropzone server implementation

I just started using the dropzone plugin and i'm using laravel in my project. I want to know how to get the files uploaded so i can store them in my database. this is my view :
<form action="{{route('realisation.storeimg')}}" method="POST" files="true" enctype="multipart/form-data"
data-toggle="validator" role="form" class="dropzone" id="my-awesome-dropzone">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="table table-striped" class="files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail/></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start</span>
</button>
<button data-dz-remove class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
<button data-dz-remove class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
<input type="hidden" name="realisation_id" value="{{$realisation->id}}">
</form>
my route for the upload:
Route::post('/storeimg',[
'as'=>'realisation.storeimg',
'uses'=>'RealisationController#storeimg'
]);
my controller:
public function storeimg (Request $request)
{
$realisation = Realisation::where('id','realisation_id')->first();
if($request->file('image')) {
foreach ($request->file('image') as $image) {
$realisation_image = Realisationimg::where('realisation_id','realisation_id')->first();
File::delete($realisation_image->image);
File::delete($realisation_image->image_thumb);
$extension = $image->getClientOriginalExtension();
$name = substr($image->getClientOriginalName(), 0, -4);
list($width, $height) = getimagesize($image);
$imgname = str_slug($name, '_');
$filename = $imgname.'.'.$extension;
if(file_exists('uploads/realisationimg/cover/' . $filename)){
do {
$newname = $imgname.'_'.str_random(3) . '.' . $extension;
}
while(file_exists('uploads/realisationimg/cover/' . $newname));
$filename = $newname;
}
$path = 'uploads/realisationimg/cover/'.$filename;
$path_thumb = 'uploads/realisationimg/thumb/'.$filename;
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path);
$save = Image::make($image->getRealPath())->resize(1600, null, function ($constraint){
$constraint->aspectRatio();
})->save($path_thumb);
$realisation_image->image = $path;
$realisation_image->image_thumb = $path_thumb;
$realisation_image->realisation_id = $id;
$realisation_image->save();
}
}
Session::flash('ajouter','ok');
return redirect(route('realisation.edit',['id'=>$request->get('realisation_id')]));
}
in the dropzone.js file i changed the default options to the following:
uploadMultiple: true,
paramName: "image",
when i submit the dropzone form nothing gets executed (no files are stored and nothing in my database). can someone point to me my mistake? thanks.
Here is s sample code that might help.
Route:
Route::post('/storeimg', 'GalleryController#storeimg')
->name('realisation.storeimg');
Controller:
public function storeimg(Request $request)
{
$path = $request->file('file')->store('public/photo');
if (!$path)
return url('storage');
$dirs = explode('/', $path);
if ($dirs[0] === 'public')
$dirs[0] = 'storage';
$data['image'] = url(implode('/', $dirs));
Photo::create($data);
session()->flash('success', 'Photos uploaded successfully');
return response()->json(['success'=>$data['image']]);
}
View: Just open file to send files to controller.
{!! Form::open([ 'route' => [ 'realisation.storeimg'], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{!! Form::close() !!}
<link rel="stylesheet" href="../dropzone.min.css">
<script src="../dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize : 1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
//Remove Photo
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
console.log(id);
$.ajax({
dataType: 'json',
type:'delete',
url: url + '/' + id,
}).done(function(data){
c_obj.remove();
});
});
</script>
This is result in a dropzone box where you can add multiple photos at a time

Codeigniter Mysql Ajax Pagination sort and search

I have to do a codeigniter crud operation. But now i want to add pagination search and sort for that.I used lots of tutorials to do that. But i can't understand. To anyone who knows please help me to do that. Thank you.
controller
class User_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->library('form_validation');
}
// load user_list view
public function index()
{
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_list');
}
// show all the users in view
public function fillgrid(){
$this->user_model->fillgrid();
}
function fetch_record(){
$this->user_model->fetch_record();
}
// validate and insert new user data
public function create(){
$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{
$this->user_model->create();
}
}
// edit user
public function edit(){
$id = $this->uri->segment(3);
$this->db->where('id',$id);
$data['query'] = $this->db->get('user');
$data['id'] = $id;
$this->load->view('admin_pages/user_edit', $data);
}
// update validation
public function update(){
$res['error']="";
$res['success']="";
$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){
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else{
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'));
$this->db->where('id', $this->input->post('hidden'));
$this->db->update('user', $data);
$res['success'] = '<div class="alert alert-success">One record updated Successfully</div>';
}
header('Content-Type: application/json');
echo json_encode($res);
exit;
}
//delete user
public function delete(){
$id = $this->input->POST('id');
$this->db->where('id', $id);
$this->db->delete('user');
echo'<div class="alert alert-success">One record deleted Successfully</div>';
exit;
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function fillgrid(){
$this->db->order_by("id", "desc");
$data = $this->db->get('user');
foreach ($data->result() as $row){
$edit = base_url().'index.php/user_controller/edit/';
$delete = base_url().'index.php/user_controller/delete/';
echo "<tr>
<td>$row->firstname</td>
<td>$row->lastname</td>
<td>$row->email</td>
<td>$row->contact_no</td>
<td>$row->address</td>
<td>$row->created</td>
<td><a href='$edit' data-id='$row->id' class='btnedit' title='edit'><i class='glyphicon glyphicon-pencil' title='edit'></i></a> <a href='$delete' data-id='$row->id' class='btndelete' title='delete'><i class='glyphicon glyphicon-remove'></i></a></td>
</tr>";
}
exit;
}
public function create(){
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'),
'created'=>date('d/m/y'));
$this->db->insert('user', $data);
echo'<div class="alert alert-success">One record inserted Successfully</div>';
exit;
}
private function edit(){}
private function delete(){}
//2015.7.26
//set table name to be used by all functions
var $table = 'user';
function fetch_record($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get($this->user);
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function record_count()
{
return $this->db->count_all_results('user');
}
//2015.7.26
}
//2015.7.26
public function pagination(){
$page_number = $this->input->post('page_number');
$item_par_page = 2;
$position = ($page_number*$item_par_page);
$result_set = $this->db->query("SELECT * FROM user LIMIT ".$position.",".$item_par_page);
$total_set = $result_set->num_rows();
$page = $this->db->get('user') ;
$total = $page->num_rows();
//break total recoed into pages
$total = ceil($total/$item_par_page);
if($total_set>0){
$entries = null;
// get data and store in a json array
foreach($result_set->result() as $row){
$entries[] = $row;
}
$data = array(
'TotalRows' => $total,
'Rows' => $entries
);
$this->output->set_content_type('application/json');
echo json_encode(array($data));
}
exit;
}
view
<div class="well">
<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/user_controller/create" method="POST">
<!--First Name-->
<div class="form-group">
<label class="sr-only" for="firstname">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First name">
</div>
<!--/First Name-->
<!--Last Name-->
<div class="form-group">
<label class="sr-only" for="lastname">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name">
</div>
<!--/Last Name-->
<!-- email-->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">#</div>
<input class="form-control" name="email" type="email" placeholder="Enter email">
</div>
</div>
<!-- email-->
<!--Contact-->
<div class="form-group">
<label class="sr-only" for="contact_no">Contact</label>
<input type="text" class="form-control" name="contact_no" id="contact_no" placeholder="contact number">
</div>
<!--/Contact-->
<!--Address-->
<div class="form-group">
<label class="sr-only" for="address">Address</label>
<input type="text" name="address" class="form-control" id="exampleInputPassword2" placeholder="Address">
</div>
<!--/Address-->
<!--submit-->
<input type="submit" class="btn btn-success" id="exampleInputPassword2" value="submit">
<!--/submit-->
</div>
</form>
</div>
<table class="table">
<thead><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Contact</th><th>Address</th><th>created</th><th>Action</th></tr></thead>
<tbody id="fillgrid">
</tbody>
<tfoot></tfoot>
</table>
<!-- //2015.7.26-->
<div class="row clear-fix">
<div class="col-md-4 pull-right">
<button id="previous" class="btn btn-sm btn-primary">Previous</button>
<lable>Page <lable id="page_number" name="page_number" ></lable> of <lable id="total_page" name="total_page"></lable></lable>
<button id="next" class="btn btn-sm btn-primary">Next</button>
</div>
</div>
<div style="text-align: center">
<!--//2015.7.26-->
</div>
</div>
</div>
<script>
$(document).ready(function (){
//fill data
var btnedit='';
var btndelete = '';
fillgrid();
// add data
$("#frmadd").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:data
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
function fillgrid(){
$("#loader").show();
$.ajax({
url:'<?php echo base_url() ?>index.php/user_controller/fillgrid',
type:'GET'
}).done(function (data){
$("#fillgrid").html(data);
$("#loader").hide();
btnedit = $("#fillgrid .btnedit");
btndelete = $("#fillgrid .btndelete");
var deleteurl = btndelete.attr('href');
var editurl = btnedit.attr('href');
//delete record
btndelete.on('click', function (e){
e.preventDefault();
var deleteid = $(this).data('id');
if(confirm("are you sure")){
$("#loader").show();
$.ajax({
url:deleteurl,
type:'POST' ,
data:'id='+deleteid
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
}
});
//edit record
btnedit.on('click', function (e){
e.preventDefault();
var editid = $(this).data('id');
$.colorbox({
href:"<?php echo base_url()?>index.php/user_controller/edit/"+editid,
top:50,
width:500,
onClosed:function() {fillgrid();}
});
});
});
}
});
</script>
i think you have to check your db field name it will work definitely you are missing some db field name...

Resources