Insert data in codeigniter - model-view-controller

I am trying to make an insert function in codeigniter using php and bootstrap. But when i press add button, nothing happens, my new data are not added in my db table. Please Help me.
My code:
department.php
<?php
/*
* File Name: employee.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the employee model
$this->load->model('department_model');
}
//index function
function index()
{
//fetch data from department and designation tables
// $data['department'] = $this->department_model->get_department();
//set validation rules
$this->form_validation->set_rules('id', 'Employee ID', 'trim|required|numeric');
$this->form_validation->set_rules('department_emer', 'Department Name', 'trim|required|callback_alpha_only_space');
$this->form_validation->set_rules('pershkrimi', 'Description', 'trim|required');
//$this->form_validation->set_rules('id_departament', 'Department', 'callback_combo_check');
if ($this->form_validation->run() == FALSE)
{
//fail validation
$this->load->view('department_view');
}
else
{
//pass validation
$data = array(
//'id' => $this->input->post('id'),
'department_emer' => $this->input->post('department_emer'),
'pershkrimi' => $this->input->post('pershkrimi'),
);
//insert the form data into database
$this->db->insert('department', $data);
//display success message
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Department details added to Database!!!</div>');
redirect('department/index');
}
}
//custom validation function to accept only alpha and space input
function alpha_only_space($str)
{
if (!preg_match("/^([-a-z ])+$/i", $str))
{
$this->form_validation->set_message('alpha_only_space', 'The %s field must contain only alphabets or spaces');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
department_model.php
<?php
/*
* File Name: employee_model.php
*/
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get department table to populate the department name dropdown
}
?>
department_view.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter | Insert Employee Details into MySQL Database</title>
<!--link the bootstrap css file-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- link jquery ui css-->
<link href="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.css'); ?>" rel="stylesheet" type="text/css" />
<!--include jquery library-->
<script src="<?php echo base_url('assets/js/jquery-1.10.2.js'); ?>"></script>
<!--load jquery ui js file-->
<script src="<?php echo base_url('assets/jquery-ui-1.11.2/jquery-ui.min.js'); ?>"></script>
<style type="text/css">
.colbox {
margin-left: 0px;
margin-right: 0px;
}
</style>
<script type="text/javascript">
//load datepicker control onfocus
$(function() {
$("#hireddate").datepicker();
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-offset-3 col-lg-6 col-sm-6 well">
<legend>Add Department Details</legend>
<?php
$attributes = array("class" => "form-horizontal", "id" => "departmentform", "name" => "departmentform");
echo form_open("department/index", $attributes);?>
<fieldset>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="department_emer" class="control-label">Name</label>
</div>
<div class="col-lg-8 col-sm-8">
<input id="department_emer" name="department_emer" placeholder="department_emer" type="text" class="form-control" value="<?php echo set_value('department_emer'); ?>" />
<span class="text-danger"><?php echo form_error('department_emer'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row colbox">
<div class="col-lg-4 col-sm-4">
<label for="mbiemer" class="control-label">Description</label>
</div>
<div class="col-lg-8 col-sm-8">
<textarea class="form-control" rows="5" id="pershkrimi" name="pershkrimi" placeholder="pershkrimi" value="<?php echo set_value('pershkrimi'); ?>" ></textarea>
<span class="text-danger"><?php echo form_error('pershkrimi'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-md-8 text-left">
<input id="btn_update" name="btn_update" type="submit" class="btn btn-primary" value="Add" />
<input id="btn_cancel" name="btn_cancel" type="reset" class="btn btn-danger" value="Cancel" />
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</div>
</div>
</div>
</body>
</html>

In department.php replace
$this->db->insert('department', $data);
with
$this->load->model('department_model.php');
$this->department_model.php->insert($data);
And in department_model.php create a function insert
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success message or anything which you want
}
}
This will solve your problem.
Let me know if you require any further help!!!

Please load the CI database library before inserting the data, or you can load it in your constructor method.
$this->load->library('database');
Hopefully it can help you.

Related

Redirect to login page instead of going to dashboard page after successful login in laravel.please help me to solve query

'Redirect to login page instead of going to dashboard page after successful login in laravel.please help me to solve query.I have tried a lot but i cannot find solution.Any help will be appreciated.I have changes form actions but it seems same results ..........................................................................
login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AdminLTE 3 | Log in</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="{{asset('plugins/fontawesome-free/css/all.min.css')}}">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Tempusdominus Bootstrap 4 -->
<link rel="stylesheet" href="{{asset('plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css')}}">
<!-- iCheck -->
<link rel="stylesheet" href="{{asset('plugins/icheck-bootstrap/icheck-bootstrap.min.css')}}">
<!-- JQVMap -->
<link rel="stylesheet" href="{{asset('plugins/jqvmap/jqvmap.min.css')}}">
<!-- Theme style -->
<link rel="stylesheet" href="{{asset('dist/css/adminlte.min.css')}}">
<!-- overlayScrollbars -->
<link rel="stylesheet" href="{{asset('plugins/overlayScrollbars/css/OverlayScrollbars.min.css')}}">
<!-- Daterange picker -->
<link rel="stylesheet" href="{{asset('plugins/daterangepicker/daterangepicker.css')}}">
<!-- summernote -->
<link rel="stylesheet" href="{{asset('plugins/summernote/summernote-bs4.min.css')}}">
<link rel="stylesheet" href="{{asset('plugins/fontawesome-free/css/all.min.css')}}">
<!-- DataTables -->
<link rel="stylesheet" href="{{asset('plugins/datatables-bs4/css/dataTables.bootstrap4.min.css')}}">
<link rel="stylesheet" href="{{asset('plugins/datatables-responsive/css/responsive.bootstrap4.min.css')}}">
<link rel="stylesheet" href="{{asset('plugins/datatables-buttons/css/buttons.bootstrap4.min.css')}}">
<!-- Theme style -->
<link rel="stylesheet" href="{{asset('dist/css/adminlte.min.css')}}">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="{{asset('plugins/jquery/jquery.min.js')}}"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<!-- jQuery UI 1.11.4 -->
<script src="{{asset('plugins/jquery-ui/jquery-ui.min.js')}}"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="{{asset('plugins/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<!-- ChartJS -->
<script src="{{asset('plugins/chart.js/Chart.min.js')}}"></script>
<!-- Sparkline -->
<script src="{{asset('plugins/sparklines/sparkline.js')}}"></script>
<!-- JQVMap -->
<script src="{{asset('plugins/jqvmap/jquery.vmap.min.js')}}"></script>
<script src="{{asset('plugins/jqvmap/maps/jquery.vmap.usa.js')}}"></script>
<!-- jQuery Knob Chart -->
<script src="{{asset('plugins/jquery-knob/jquery.knob.min.js')}}"></script>
<!-- daterangepicker -->
<script src="{{asset('plugins/moment/moment.min.js')}}"></script>
<script src="{{asset('plugins/daterangepicker/daterangepicker.js')}}"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="{{asset('plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js')}}"></script>
<!-- Summernote -->
<script src="{{asset('plugins/summernote/summernote-bs4.min.js')}}"></script>
<!-- overlayScrollbars -->
<script src="{{asset('plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js')}}"></script>
<!-- AdminLTE App -->
<script src="{{asset('dist/js/adminlte.js')}}"></script>
<!-- AdminLTE for demo purposes -->
<script src="{{asset('dist/js/demo.js')}}"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="{{asset('dist/js/pages/dashboard.js')}}"></script>
<script src="{{asset('plugins/jquery/jquery.min.js')}}"></script>
<!-- Bootstrap 4 -->
<script src="{{asset('plugins/bootstrap/js/bootstrap.bundle.min.js')}}"></script>
<!-- DataTables & Plugins -->
<script src="{{asset('plugins/datatables/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('plugins/datatables-bs4/js/dataTables.bootstrap4.min.js')}}"></script>
<script src="{{asset('plugins/datatables-responsive/js/dataTables.responsive.min.js')}}"></script>
<script>
$(document).ready( function () {
$('#example1').DataTable();
} );
</script>
<script src="{{asset('plugins/datatables-responsive/js/responsive.bootstrap4.min.js')}}"></script>
<script src="plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
<script src="plugins/jszip/jszip.min.js"></script>
<script src="plugins/pdfmake/pdfmake.min.js"></script>
<script src="plugins/pdfmake/vfs_fonts.js"></script>
<script src="plugins/datatables-buttons/js/buttons.html5.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.print.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.colVis.min.js"></script>
</head>
</head>
<body class="hold-transition login-page">
<div class="">
<div class="row ">
<div class="login-box">
<div class="login-logo">
<b>Admin</b>Login
</div>
<!-- /.login-logo -->
<div class="">
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="/adminlogin" method="get">
#csrf
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Email" name="email">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" class="form-control" placeholder="Password" name="password">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox" id="remember">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-md-12 ">
<button type="submit" class="btn btn-primary btn-block">Admin Login</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center mb-3">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i> Sign in using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i> Sign in using Google+
</a>
</div>
<!-- /.social-auth-links -->
<p class="mb-1">
I forgot my password
</p>
<p class="mb-0">
Register a new membership
</p>
</div>
<!-- /.login-card-body -->
</div>
</div>
</div>
<div class="login-box">
<div class="login-logo">
<b>Normal User</b> Login
</div>
<!-- /.login-logo -->
<div class="">
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="/loginnormaluser" method="get">
#csrf
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Email" name="email">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" class="form-control" placeholder="Password" name="password">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox" id="remember">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit" class="btn btn-primary btn-block">Normal User</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center mb-3">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i> Sign in using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i> Sign in using Google+
</a>
</div>
<!-- /.social-auth-links -->
<p class="mb-1">
I forgot my password
</p>
<p class="mb-0">
Register a new membership
</p>
</div>
<!-- /.login-card-body -->
</div>
</div>
</div>
<!-- /.login-box -->
<!-- jQuery -->
</div>
</div>
</body>
</html>
<?php
// khan controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Auth;
//use Session;
class KhanController extends Controller
{
//
function show(){
return view('khn');
}
function insert(Request $request){
$first_name = $request->input('email');
$last_name = $request->input('password');
$data=array('fname'=>$first_name,"lname"=>$last_name);
DB::table('khan')->insert($data);
echo "Record inserted successfully.<br/>";
return view('khn') ;
}
function showdata(){
$data= DB::table('khan')->get();
return view('showdata',['data'=>$data]) ;
}
function edit($id){
$request= DB::table('khan')->find($id);
return view('eidt',['request'=>$request]) ;
}
function update(Request $request){
$id=$request->id;
// return $data;
$data=array('fname'=>$request->fname,'lname'=>$request->lname);
$update = DB::table('khan') ->where('id', $id) ->limit(1) ->update($data);
//return $update;
return redirect('showdata') ;
}
function delete(Request $request){
$id=$request->id;
DB::table('khan')->delete($id);
//return $update;
return redirect('showdata') ;
}
function view($id){
$request= DB::table('khan')->find($id);
return view('view',['request'=>$request]) ;
}
function register(Request $request){
$first_name = $request->input('name');
$email = $request->input('email');
$pass = $request->input('password');
$data=array('name'=>$first_name,"email"=>$email,"password"=>$pass);
DB::table('registration')->insert($data);
echo "Record inserted successfully.<br/>";
return view('login') ;
// $request= DB::table('khan')->find($id)
}
//function login(Request $request){
// $user = DB::table('registration')
// ->where('email',$request->input('email'))
// ->where('password',$request->input('password'))
// ->first();
// if($user)
// {
// $request->Session()->put('loginid',$user->id);
// return $request;
// return redirect('dashboard');
// else{
// return back()->with('fail','Email-Address And Password Are Wrong.');
// }
// echo "hhhhhhhh";
//return redirect('dashboard') ;
//}
function adminlogin(Request $request){
$user = DB::table('registration')
->where('email',$request->input('email'))
->where('password',$request->input('password'))
->first();
if($user)
{
$request->Session()->put('loginid',$user->id);
// return $request;
//echo Session('loginid');
return redirect('dashboard');
}else
{
return back()->with('fail','Email-Address And Password Are Wrong.');
}
}
function logout(Request $request){
if(Session::has('loginid')){
Session::pull('loginid');
return redirect('login');
}
}
function normaluser(Request $request){
return view('normaluser');
}
function normaluserregister(Request $request){
$first_name = $request->input('name');
$email = $request->input('email');
$pass = $request->input('password');
$data=array('name'=>$first_name,"email"=>$email,"password"=>$pass);
DB::table('normaluser')->insert($data);
echo "Record inserted successfully.<br/>";
return view('dashboard') ;
// $request= DB::table('khan')->find($id)
}
function loginnormaluser(Request $request){
$user = DB::table('normaluser')
->where('email',$request->input('email'))
->where('password',$request->input('password'))
->first();
if($user)
{
$request->Session()->put('loginid',$user->id);
// return $request;
//echo Session('loginid');
return redirect('newuser');
}else{
return back()->with('fail','Email-Address And Password Are Wrong.');
// return back()->with('fail','Email-Address And Password Are Wrong.');
}
}
}
<?php
// web.php
use Illuminate\Support\Facades\Route;
//use App\Http\Controllers\KhanController;
use App\Http\Controllers\KhanController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['middleware'=>'web'],function(){
Route::get("/addemployee",[KhanController::class,"show"]);
Route::post("/imi",[KhanController::class,"insert"]);
Route::get("/showdata",[KhanController::class,"showdata"]);
Route::get("/edit/{id}",[KhanController::class,"edit"]);
Route::get("/delete/{id}",[KhanController::class,"delete"]);
Route::get("/view/{id}",[KhanController::class,"view"]);
Route::post("/update",[KhanController::class,"update"]);
//Route::post("/update",[KhanController::class,"update"]);
Route::post("/register",[KhanController::class,"register"]);
Route::get("/login",[KhanController::class,"login"]);
Route::get("/adminlogin",[KhanController::class,"adminlogin"]);
Route::get("/logout",[KhanController::class,"logout"]);
//Route::get("/dashboard",[KhanController::class,"login"]);
Route::view('/dashboard','dashboard');
Route::get("/normaluser",[KhanController::class,"normaluser"]);
Route::post("/normaluserregister",[KhanController::class,"normaluserregister"]);
Route::get("/loginnormaluser",[KhanController::class,"loginnormaluser"]);
Route::view('/newuser','newuser');
Route::view('login','login');
});
//Route::view('/dashboard','dashboard')->middleware('isLoggedIn');
//register view
// Route::view('register','register');
// Route::view('login','login');
//Route::view("/jjj","khn");
//Route::get("/edit/{id}",[KhanController::class,"edit"]);
<?php
// middelware alreadyloggenin
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Session;
class alreadyloggenin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
//echo "hiiiii";
// if(Session()->has('loginid') && (url('login')==$request->url() || url('register')==$request->url() )){
//return back();
// }
// if(!session()->has('loginid')){
// echo"hiiiiiiiiiiiiiiiii";
// }
$path=$request->path();
if(($path=="login" || $path=="register" ) && (Session::get('loginid'))){
return redirect('/');
}
else if($path!='login' && !Session::get('loginid') && $path!='register' && !Session::get('loginid') ){
return redirect('/login');
}
return $next($request);
}
}
// group middleware
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\alreadyloggenin::class
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];```
can you put dd($user) to know which function are you using ,so we can correct the return ? for example try it with admin , because Laravel is maybe using the default login

ajax laravel not inserting or code not working

i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i dont' know why although i am writing correctly
please help
here is my code
my blade file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<div class="row" style="matgin-top:50px;">
<div class="col-md-6">
<div class="card">
<div class="card-hehader bg-primary text-white">Add new product</div>
<form id="form" action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
#csrf
#method('POST')
<div class="form-group">
<label for="">product name</label>
<input type="text" name="name" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<div class="form-group">
<label for="">product image</label>
<input type="file" name="image" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<button type="submit" class="btn btn-info">add</button>
</form>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary">All Products</div>
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
<script src="{{asset('js/app.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = this;
$.ajax({
url:$(form).attr('action'),
method:$(form).attr('method'),
data:new FormData(form),
processData:false,
dataType:'json',
contentType:false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
succes:function(data){
if(data.code == 0){
$.each(data.error, function(prefix,val){
$(form).find('span.'+prefix+'_error').text(val[0]);
});
}
else{
$(form)[0].reset();
alert(data.msg);
// fetchAllProducts();
}
}
})
});
});
</script>
</body>
</html>
and my controller store function
public function store(Request $request)
{
$path = 'files/';
$file = $request->file('product_image');
$file_name = time().'_'.$file->getClientOriginalName();
// $upload = $file->storeAs($path, $file_name);
$upload = $file->storeAs($path, $file_name, 'public');
if($upload){
Product::insert([
'name'=>$request->name,
'image'=>$request->image,
]);
return response()->json(['code'=>1,'msg'=>'New product has been saved successfully']);
}
}
I check out your controller portion and found something messy, would you mind trying with the below code:
if ($request->has('image')) {
$fileName = time() . '_' . $request->image->getClientOriginalExtension();
$request->image->storeAs('Files', $fileName, 'image');
$product = new Product();
$product->name = $request->name;
$product->image = $fileName;
$product->save();
return response()->json(['code'=>1,'msg'=>'New product has been saved
successfully']);
}

How to use CSRF token in codeigniter with Ajax Post data in database with giving 403 Error..?

* While posting data in database in codeigniter first time my data is post to database , but when second time i am try to post data in database then it give me 403 ERROR .First Time code is work ,when second time i am post it give me 403 error data is not post or save in my database. *
View Page Code :
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h2>Register</h2>
<!-- <form id="saveEmpForm"> -->
<?php
$attributes = array('id' => 'saveEmpForm');
echo form_open('register/insert', $attributes);
?>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
</div>
<button type="submit" class="btn btn-primary" id="btn_add">Submit</button>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
<script type="text/javascript">
var csrf_token = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<script type="text/javascript">
$('#saveEmpForm').submit('click',function(){
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>register/insert",
dataType : "JSON",
data : {name:name, email:email, password:password, csrf_test_name: csrf_token},
success: function(response){
$('#name').val("");
$('#email').val("");
$('#password').val("");
alert('Success');
}
});
return false;
});
</script>
</body>
</html>
Controller code:
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('register_model');
}
public function index()
{
$this->load->view('register_view');
}
public function insert(){
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result=$this->register_model->insert_data($data);
echo json_encode($data);
}
}
Model Code :
class Register_model extends CI_Model{
public function insert_data($data)
{
$this->db->insert('emp',$data);
return $this->db->insert_id();
}
}
?>```

Response is empty string

I am creating a simple upload files web application using laravel in the backend and I am trying to print the response that is sent from the server -which is supposed to be informed about the uploaded file- in the console, but it shows me an empty string.
here is my controller:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Storage;
class UploadsController extends Controller
{
public function getUpload(){
return view('upload');
}
public function postUpload(request $request){
// //
$result = print_r($request,true);
$time = Carbon::now();
if ($request->hasFile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fileName = $file->getClientOriginalName();
//$upload_success = $file->storeAs('public',$file->getClientOriginalName());
$upload_success=Storage::disk('local')->put($fileName, fopen($file, 'r+'));
if ($upload_success) {
return response()->json(['request'=>$request->getContent()], 200);
}
else {
return response()->json('error', 400);
}
}
return response()->json('no file to upload', 400);
}
}
and my view where I am printing the response:
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="/js/xhr2.js"></script>
<script type="text/javascript">
$(function(){
$('#upload').on("click",function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#file").upload("/upload",function(data){
$('#spin').css('display','none');
$('#msg').css('display','block');
console.log(data);
},function(prog,val){
$('#prog').html(val+"%");
$('#prog').width(''+val+'%');
if(val == 100){
$("#prog").html('Completed');
$('#spin').css('display','block');
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div style="margin-top:5px"><input type="file" id="file" name="file" ></div>
<div style="margin-top:5px;margin-bottom: 5px">
<input type="button" id="upload" value="upload" class="btn btn-success btn-lg">
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100" id="prog"></div>
</div>
<div id="spin" style="display:none">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
</div>
<div class="alert alert-success" style="display: none" id="msg" style="text-align: center">
<strong>Success!</strong>You have uploaded the file successfully
</div>
</div>
</body>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
and here is a sample of what I get:
I would know if I am doing it wrong, and if not, why it is empty,
Thanks.
You're not using a form element.
Wrap your inputs in a basic html form:
<form method="POST" action="#">
#csrf
...
</form>
Then use jquery to post the form to the laravel route.

(CodeIgniter) Ajax return the main layout instead of the needed view

I got a headache with the ajax return result. Can everybody show me what's wrong with my code?
I have a main layout named "home.php", some important codes in this file as belows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="<?=base_url();?>favicon.ico">
<title>IT Ebooks - Knowledge Sharing<?php if(isset($title_page)) echo " | ".$title_page ?></title>
<link href="<?=base_url();?>css/bootstrap.min.css" rel="stylesheet">
<link href="<?=base_url();?>css/font-awesome.min.css" rel="stylesheet">
<link href="<?=base_url();?>css/custom.css" rel="stylesheet">
</head>
<body>
<div id="main-content" class="col-md-9"><!--I will load the content here based on my controller & action-->
<?php
if($this->router->fetch_class()=="ListBy"){
$this->load->view("listby");
}
elseif($this->router->fetch_class()=="Home"){
$this->load->view("index");
}
elseif($this->router->fetch_class()=="User"){
if($this->router->fetch_method()=="Signup")
$this->load->view('signup.php');
}
?>
</div>
<script src="<?=base_url();?>js/jquery-3.1.1.min.js"></script>
<script src="<?=base_url();?>js/bootstrap.min.js"></script>
<script src="<?=base_url();?>js/bootbox.js"></script>
<script src="<?=base_url();?>js/listby.js"></script><!--this file do ajax function-->
</body>
</html>
My Home controller:
<?php
class Home extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->view('home.php');
}
public function index(){
//Do nothing
}
} //class
?>
My index.php file:
<section id="latest"><!--Latest upload-->
<div class="row">
<div class="col-md-8">
<p class="text-center text-primary header">Latest Uploads</p>
</div>
<div class="col-md-4">
<div class="form-inline">
<label>Books per page : </label>
<select class="form-control" id="PageSize" name="PageSize">
<option value="12" selected>12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
</div>
</div>
<div class="col-md-12" id="ajax-content">Ajax content loaded</div>
</div>
</section>
My ajax function file "listby.js":
$(document).ready(function(){
$.ajax({
type:"POST",
url:"AjaxProcessing1/loadByCategory",
data:"PageNo="+1+"&PageSize="+12,
dataType: "text",
success: function(response){
alert(response);//I used alert to show the problem
//$('#ajax-content').html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
})
My AjaxProcessing1 controller file:
<?php
class AjaxProcessing1 extends CI_Controller {
public function loadByCategory(){
$PageNo = $this->input->post('PageNo');
$PageSize = $this->input->post('PageSize');
$this->load->model('model_book');
$data['books'] = $this->model_book->get_latest_book($PageSize,$PageNo);
$this->load->view('ajax_result1',$data);
}
} //class
?>
My ajax_result1 page:
<?php
if(isset($books)){
?>
<div class="row">
<?php foreach($books as $book): ?>
<div class="col-md-3 col-sm-6">
<a href="<?=base_url();?>/ListBy/detail/<?=$book->id?>/<?=$book->slug?>">
<img class="anhsach" src="<?=base_url();?>img/cover/<?=$book->image;?>" alt="<?=$book->slug;?>"/>
</a>
</div>
<?php endforeach; ?>
</div>
<?php
}
?>
So, until here. Everything's OK when I'm in home page, the ajax function return the ajax_result1 as expected
[Pic1 - Load as expected][1]
But, when I'm in ListBy controller, the return of the ajax function is the main layout?
My ListBy Controller:
<?php
class ListBy extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('model_book');
}
public function index(){
//Nothing to do here
}
public function ListByCategory($category_id){
$data['title_page'] = "List by category";
$data['num_books'] = $this->model_book->number_of_books_bycategory($category_id);
$data['category_id'] = $category_id;
$this->load->view('home.php',$data);
}
} //class
?>
My listby.php file:
<?php
echo "<h3 class='text-center text-success'>".$num_books." book(s) found</h3>"
?>
<section id="cate">
<div class="row">
<div class="col-md-8">
<p class="text-center text-primary header">Select your books view per page</p>
</div>
<div class="col-md-4">
<div class="form-inline">
<label>Books per page : </label>
<select class="form-control" id="PageSize" name="PageSize">
<option value="12" selected>12</option>
<option value="24">24</option>
<option value="36">36</option>
</select>
</div>
</div>
<div class="col-md-12" id="ajax-content">Ajax content loaded</div>
</div>
</section>
<input type="hidden" id="total_record" value="<?=$num_books?>"/>
<input type="text" id="category_id" value="<?=$category_id?>"/>
<div class="row text-center">
<ul class="pagination">
</ul>
</div>
And the result I got when I'm in this controller (return the main layout):
[Not as expected][2]
So, what's going on with my code. Thanks so much for any help or suggestion in advanced.
[1]: https://i.stack.imgur.com/PeADW.png
[2]: https://i.stack.imgur.com/PAiO1.png
My project link in case you need: http://www.mediafire.com/file/ed1e31od1fk5vkg/itebooks-23Oct16.zip
Home extends CI_Controller { public function __construct() { parent::__construct(); //$this->load->view('home.php');
// THE PROBLEM is : you can't load the main/home layout in Home controller construct function }

Resources