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

* 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();
}
}
?>```

Related

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 call edit method of the resource controller using AJAX in Laravel5.6

In my laravel project I am using resource controller for update. but it is not working. I tried but it failed.
my blade
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>{{ config('app.name') }}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>{{ config('app.name') }}</h1>
<form class="dis-none" id="FormAjax">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" rows="3" id="address"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" id="country" />
</div>
</div>
</div>
<button type="submit" id="SaveAjax" class="btn btn-success">Save Form</button>
<button type="button" id="cancel" class="btn btn-danger">Cancel</button>
</form>
<div id="ShowAjax" class="row">
<button type="button" id="AddForm" class="btn btn-success">Add Form</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#AddForm").click(function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
$('#UpdateForm').text('Save Form');
});
$("#SaveAjax").click(function () {
$("#FormAjax").hide();
$("#ShowAjax").fadeIn();
});
$(document).on('click', '#cancel', function () {
$('#name').val('');
$('#country').val('');
$('#address').val('');
});
$(document).on('click', '#edit', function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
name = $(this).parent().parent().find('#ename').text();
address = $(this).parent().parent().find('#eaddress').text();
country = $(this).parent().parent().find('#ecountry').text();
$('#name').val(name);
$('#address').val(address);
$('#country').val(country);
$('#SaveAjax').text('Edit');
$('#SaveAjax').prop('id', 'UpdateForm');
$('#UpdateForm').attr('data-id', $(this).data('id'));
});
$(document).on('click', '#UpdateForm', function () {
name = $('#name').val();
country = $('#country').val();
address = $('#address').val();
url = "peoples";
id = $(this).data('id');
editUrl = url + '/' + id + '/edit';
$.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
console.log('success');
});
});
});
</script>
</body>
</html>
route/web.php
Route::resource('peoples', 'PeopleController');
PeopleController.php
public function edit(People $people)
{
if($request->ajax()) {
$request->validate([
'name' => 'required',
'address' => 'required',
'country' => 'required',
]);
$people = People::find($request->id);
$people->name = $request->name;
$people->address = $request->address;
$people->country = $request->country;
$people->save();
return response()->json();
}
}
When I try type in browser http://localhost:8000/peoples I see this error.
Route [editUrl] not defined. (View: C:\xampp\htdocs\Tutorials
Laravel\Ajax\resources\views\peoples.blade.php)
You cannot use the route() helper here as you have not named your routes. Instead, try using the url() helper to generate the URL.
url(id . '/edit')
But, here I see another problem as the id will come in dynamically when the JS executes by which time the Laravel helper would have already executed. So, I would suggest the following approach:
url = {{ base_url() }} + '*apiPrefix*' + '/peoples/' + id + '/edit'

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.

Insert data in codeigniter

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.

(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