Route:
This is my Route
Route::get('admin/category', 'CategoryController#category')->name('category');
Route::post('admin/category_add', 'CategoryController#add_category')-
>name('add_category');
Mycontroller:
This is my controller function
public function add_category(Request $request){
$name = $request->input('name');
$city = $request->input('status');
DB::table('categorys')->insert(['name' => $name, 'status' => $city]);
return redirect()->back()->with('message', 'SuccessFully Insert');
}
Form:
<form id="category">
<input type="name" name="name" class="form-control" id="name">
<input type="radio" value="1" id="status" name="status">
<input type="radio" value="2" id="status" name="status">
<input type="submit" value="Subscribe" name="subscribe"
id="submit">
<input type = "hidden" id="token" name = "_token" value = "<?php echo csrf_token(); ?>">
</form>
Jquery Ajax:This my jquery ajax function How to insert into database
$("#submit").click(function(event) {
$.ajax({
var name = $("input#name").val();
var status = $("input#status").val();
data: {name: name,status:status,"_token": "{{ csrf_token() }}"},
type: "post",
dataType: 'json',
url: "{{url('admin/category_add')}}",
},
success: function(data){}
});
});
correct add_category:
public function add_category(Request $request){
$category = new App\Category();
$category->name = $request->input('name');
$category->status = $request->input('status');
$category->save();
return response()->json('ok');
}
Related
I m trying to login this from with ajax but ajax dont work :( can you help me
My Controller
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'password' => 'required',
'email' => 'required|email',
]);
if ($validator->passes()) {
if (auth()->attempt(array('email' => $request->input('email'),
'password' => $request->input('password')),true))
{
return response()->json(["status" => true]);
}
return response()->json(['error'=>false]);
}
return response()->json(['error'=>$validator->errors()]);
}
my View
<div id="giris-yap" class="ekran" x-show="tab === 'giris-yap'">
<form action="javascript:void(0)" id="loginform" action="{{ route('giris') }}" method="post">
#csrf
<div class="form-group">
<input type="email" name="email" id="email" placeholder="E-Posta"
#error('email') style="border-color:red" #enderror>
<label class="lab" for="email">E-Posta</label>
<small style="color: red;" id="email" class="text-danger error-text email_err hata"></small>
</div>
<div class="password-input form-group">
<input type="password" name="password" id="password" placeholder="Şifre"
#error('password') style="border-color:red" #enderror>
<label class="lab" for="password">Şifre</label>
<span toggle="#password" class="fa fa-fw fa-eye field-icon toggle-password"></span>
<small style="color: red;" id="password" class="text-danger error-text password_err hata"></small>
</div>
<div class="remember col-2 gap-10">
<div class="form-check">
<label><input type="checkbox" name="remember"> Beni Hatırla</label>
</div>
<span class="password-request">
Şifremi Unuttum
</span>
</div>
<small id="mydiv" style="color: red; margin-top: 5px; margin-bottom: 10px; display: none " class="text-danger password_err">Lütfen Eposta ve Şifrenizi Kontrol edin.</small>
<button type="submit" class="btn loginBtn">Giriş Yap</button>
</form>
my ajax
<script>
//login ajax
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "{{ route('giris') }}",
type:'POST',
data:{'_token' : '{{ csrf_token() }}', email:email, password:password},
success: function(data) {
printMsg(data)
if(data.status === true)
{
console.log(data.status)
window.location.href = '/';
}
if(data.error === true){
console.log(data.error)
$('#mydiv').show()
}
},
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
</script>
do not pass route just pass in form open tag #csrf and on button Sign In and then
in js script like this. function login(){ $.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
$.ajax({ type : 'POST', url: '{{route('login.check')}}', data : data,success : function(response) {console.log(response); if(response == 1) {
window.location.replace('{{route('test.index')}}'); }else if(response == 3)
{ $("#err").hide().html("Username or Password Incorrect. PleaseCheck").fadeIn('slow'); } } });}
I have an admin panel and I am currently working on the change password module. I have done the code for change password but for some reason the session is destroyed and user is logged out after changing the password. How to prevent the auto logout from happening. Please help me.
HTML
<form id="changepasswordform">
<input type="hidden" name='_token' value="{{ csrf_token() }}">
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label>Password</label>
</div>
<div class="col-md-10">
<div class="custom_error_msg password_error"></div>
<input type="password" name="password" class="form-control password">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label>Confirm Password</label>
</div>
<div class="col-md-10">
<div class="custom_error_msg confirm_password_error"></div>
<input type="password" name="confirm_password" class="form-control confirm_password">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<button class="btn btn-success float-right"><i class="far fa-save"></i> Save</button>
</div>
</div>
</div>
</form>
Controller
public function ChangePasswordProcess(Request $request){
/*User::find(auth()->user()->id)
->update([
'password'=> Hash::make($request->password)
]);*/
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success']);
}
Javascript
<script>
$(document).ready(function(){
$(".dropify").dropify();
$("#changepasswordform").submit(function(e){
e.preventDefault();
var status=false;
if($(".password").val()==""){
$(".password_error").html("Field is mandatory");
$(".password_error").show();
status=false;
} else {
$(".password_error").hide();
status=true;
}
if($(".confirm_password").val()==""){
$(".confirm_password_error").html("Field is mandatory");
$(".confirm_password_error").show();
status=false;
} else {
$(".confirm_password_error").hide();
status=true;
}
if($(".password").val()!=="" && $(".confirm_password").val()!==""){
if($(".password").val() !== $(".confirm_password").val()){
$(".confirm_password_error").html("Passwords don't match");
$(".confirm_password_error").show();
status=false;
} else {
$(".confirm_password_error").hide();
status=true;
}
}
if(status==true){
var formdata = new FormData(document.getElementById('changepasswordform'));
$.ajax({
url: "{{ route('admin.change_password_process') }}",
type: "post",
async: false,
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function (res) {
if (res.status == 'success') {
Swal.fire({
icon: 'success',
title: 'Success',
text: 'Password updated successfully',
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false,
}).then(function (result) {
window.location.reload();
});
}
}
});
}
});
});
</script>
On the method ChangePasswordProcess in the controller, you have to re-authenticate the user which his password changed
public function ChangePasswordProcess(Request $request){
/*User::find(auth()->user()->id)
->update([
'password'=> Hash::make($request->password)
]);*/
$userId = Auth::User()->id;
$user = User::find($userId);
$user->password = Hash::make($request->password);
$user->save();
Auth::login($user);
return response()->json(['status' => 'success']);
}
When the password_hash of the session is different from the current auth()->user() the laravel will automatically logout the user. This is done on this middleware:
vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php
If you update the password_hash on the session with the new hash password the user will be not logout.
session()->put([
'password_hash_' . auth()->getDefaultDriver() => $user->getAuthPassword()
]);
Example:
session()->put([
'password_hash_web' => "$2y$10$...hashpasswordstoredondatabase"
]);
I wrote a small script that updates the information on the page when editing. Everything basically works as it should, but I just can’t update the image. I don’t understand what the matter is. Without a script, with a page reload, everything works as it should.
Ajax script
<script type="text/javascript">
$("document").ready(function() {
$("#editPostButton{{$post->id}}").click(function() {
var formData = $("#EditPostForm{{$post->id}}").serialize();
$.ajax({
url: "{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}",
type: "POST",
data: formData,
success: function(data) {
$("#textpostdata{{$post->id}}").html($(data).find("#textpostdata{{$post->id}}").html());
$("#closeButton{{$post->id}}").click();
}
});
});
});
</script>
My Controller
public function editPost(Request $request, $id, $postId) {
$validator = $this->validate($request,[
'title' => 'max:100',
'message' => 'max:5000',
'img' => 'mimes:jpeg,png,gif,jpg|max:5000',
'videoPost' => 'max:100'
]);
if($validator) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/'.Auth::user()->id.'/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
return redirect()->back();
}
}
And update form
<form action="{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}" method="post" enctype="multipart/form-data" id="EditPostForm{{$post->id}}" name="postForm">
#csrf #method('PATCH')
<div class="form-group">
<textarea maxlength="100" name="title" class="form-control" rows="1">{{$post->title}}</textarea>
</div>
<div class="form-group">
<textarea id="message" maxlength="5000" name="message" class="form-control" rows="10">{{$post->message}}</textarea>
</div>
<div class="form-group">
<textarea maxlength="100" class="form-control mt-1" id="videoPost" name="videoPost" cols="100" rows="1">{{$post->videoPost}}</textarea>
</div>
<h6>Current image</h6>
<img src="{{$post->img}}" class="img-fluid mb-2" width="230">
<div class="form-group">
<input type="file" id="img" name="img" accept="image/*">
</div>
<button type="button" class="btn btn-sm btn-primary" id="editPostButton{{$post->id}}">Edit</button>
</form>
I have a dropdown for students_id. Now I want to track the student name and class from another table when someone select any student id. I did something for that using ajax. Its not showing me any error in the console but just giving me null array and I think thats the problem related to the query. You can check my code below. :)
//Controller
public function create()
{
$students = Student::pluck('student_id', 'id')->all();
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request) {
$students = DB::table("students")->where("student_id", $request->student_id)->pluck("student_id","id");
return json_encode($students);
}
//View and Ajax
<div class="form-group">
<label for="title">Select Student <span style="color: red">*</span></label>
<select name="student_id" class="form-control bg-dark text-white" >
<option>Select Student</option>
#foreach ($students as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">Student Full Name <span style="color: red">*</span></label>
<input name="std_name" type="text" required class="form-control" />
</div>
<div class="form-group">
<label class="control-label">Class <span style="color: red">*</span></label>
<input name="std_class" type="text" required class="form-control" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="student_id"]').on('change', function() {
var studentInfo = $(this).val();
if(studentInfo) {
$.ajax({
url: '/reports/ajax/'+studentInfo,
type: "GET",
dataType: "json",
success:function(data) {
$('input[name="std_name"]').empty();
$.each(data, function(key, value) {
$('select[name="std_name"]').append('<input value="'+ key +'">'+ value +'/>');
});
}
});
}else{
$('select[name="std_name"]').empty();
}
});
});
</script>
//Routes
Route::get('reports/ajax/{id}',array('as'=>'reports.ajax','uses'=>'ReportController#reportsAjax'));
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
]]);
Try this for your queries:
public function create()
{
$students = Student::all()->only(['student_id', 'id']);
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request)
{
$students = DB::table('students')->where('student_id', $request->student_id)->only(['student_id','id']);
return response()->json($students, 200);
}
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...