Json_encode array function Error - php

I have make an matrix for boxing products in to different boxed based on that assumption:
I am using PHP as an server side language and jQuery Ajax for transmitting the data.
Front end code: <input id="no_of_post" name="no_of_post" type="text" class="form-control" onChange="return test()">
<div class="col-sm-3">
<label for="lastname">Weight Box</label><br>
<input id="weight_box" name="weight_box" type="text" class="form-control">
</div>
<div class="col-sm-3">
<label for="lastname">Plate Box</label><br>
<input id="plate_box" name="plate_box" type="text" class="form-control">
</div>
<div class="col-sm-3">
<label for="lastname">Two Pipe Box</label><br>
<input id="two_pipe_box" name="two_pipe_box" type="text" class="form-control">
</div>
<div class="col-sm-3">
<label for="lastname">Four Pipe Box</label><br>
<input id="four_pipe_box" name="four_pipe_box" type="text" class="form-control" onChange="return test()">
</div>
<div class="col-sm-3">
<label for="lastname">No. Of Box</label><br>
<input id="no_of_box" name="no_of_box" type="text" class="form-control">
</div>
<script type="text/javascript">
function test(){
var no_of_post=$('#no_of_post').val();
$.ajax({
type: "POST",
url: '<?php echo base_url()?>Test/test1',
data: {no_of_post:no_of_post},
//data: $('#enqCapture').serialize(),
success: function(resp) {
// toastr.success('Success - Dispatch Detail Prepared');
$("#weight_box").val(resp[1]);
$("#plate_box").val(resp[3]);
$("#two_pipe_box").val(resp[5]);
$("#four_pipe_box").val(resp[7]);
$("#no_of_box").val(resp[9]);
console.log(resp);
},
error: function (jqXHR, exception) {
toastr.error('Error - Something wrong try again.');
}
});
return false;
}
</script>
And My Controller code is:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends MY_Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('Enquiry_model');
$this->load->model('Quotation_model');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('User');
$this->load->model('Main_model');
$this->load->model('Master_model');
$this->is_logged_in();
}
public function index(){
$data['user_data']=$this->is_logged_in();
$this->load->view('admin1/quotation/test',$data);
}
public function test1(){
$no_of_post=$this->input->post('no_of_post');
//$no_of_post."<br>";
$weight_box=0;
$plate_box=0;
$two_pipe_box=0;
$four_pipe_box=0;
if($no_of_post==1){
$weight_box=1;
$two_pipe_box=1;
$total_box=floor($weight_box+$two_pipe_box);
}else{
$weight_box=round($no_of_post/2);
$plate_box=ceil(($no_of_post/5));
$four_pipe_box=$no_of_post/4;
if (strpos($four_pipe_box,'.') !== false) {
$four_pipe_box1=floor($four_pipe_box);
$fraction=$four_pipe_box-$four_pipe_box1;
if($fraction>=.60){
$four_pipe_box=ceil($no_of_post/4);
$total_box=floor($weight_box+$plate_box+$four_pipe_box);
}else{
$four_pipe_box=floor($no_of_post/4);
$two_pipe_box=1;
$total_box=floor($weight_box+$plate_box+$four_pipe_box+$two_pipe_box);
}
}else{
$four_pipe_box=ceil($no_of_post/4);
$total_box=floor($weight_box+$plate_box+$four_pipe_box);
}
}
$arr= array($weight_box,$plate_box,$two_pipe_box,$four_pipe_box,$total_box);
/*$arr[0]=$weight_box;
$arr[1]=$plate_box;
$arr[2]=$two_pipe_box;
$arr[3]=$four_pipe_box;
$arr[4]=$total_box;*/
//$arr[0] = "Mark Reed";
//$arr[1] = "34";
//$arr[2] = "Australia";
//echo json_encode($arr);
echo json_encode(array_values($arr));
//exit();
}
}
?>
But it is return wrong result in text box.

Use:
dataType : 'json',
encode : true
After:
data: {no_of_post:no_of_post},
Because you are returning json encoded data from the controler.

Related

Select ajax with an app built using CodeIgniter

I have a company_model and a controller. I also have 3 corresponding tables in a database for where the data is saved and read from. The goal of this is to manage companies linked to sub holdings and the corresponding directors of the sub holdings.
When I add a new company, the Sub holding and Director fields work perfectly. My issue is when editing an already saved company, the corresponding Director field is not populated or populating. I have been trying to find the issue for sometime now, I am not receiving any console errors or Network XHR when checking with Chrome. I know this is going to be a simple fix, I can not see it or find the issue. Any advice or pointers would be greatly appreciated
The Database structure is as follows:
Table 1 is for the director information (director_id, director_name, director_subholding_id)
Table 2 is for subholding information (subholding_id, subholding_name)
Table 3 is for company information (company_id, company_name, ceo_name, company_subholding_id,
company_director_id)
Company_Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company_model extends CI_Model{
function get_subholding(){
$query = $this->db->get('subholding');
return $query;
}
function get_director($subholding_id){
$query = $this->db->get_where('director', array('director_subholding_id' => $subholding_id));
return $query;
}
function save_company($company_name,$subholding_id,$director_id,$ceo_name){
$data = array(
'company_name' => $company_name,
'ceo_name' => $ceo_name,
'company_subholding_id' => $subholding_id,
'company_director_id' => $director_id
);
$this->db->insert('company',$data);
}
function get_company(){
$this->db->select('company_id,company_name,ceo_name,subholding_name,director_name');
$this->db->from('company');
$this->db->join('subholding','company_subholding_id = subholding_id','left');
$this->db->join('director','company_director_id = director_id','left');
$query = $this->db->get();
return $query;
}
function get_company_by_id($company_id){
$query = $this->db->get_where('company', array('company_id' => $company_id));
return $query;
}
function update_company($company_id,$company_name,$subholding_id,$director_id,$ceo_name){
$this->db->set('company_name', $company_name);
$this->db->set('ceo_name', $ceo_name);
$this->db->set('company_subholding_id', $subholding_id);
$this->db->set('company_director_id', $director_id);
$this->db->where('company_id', $company_id);
$this->db->update('company');
}
//Delete Product
function delete_company($company_id){
$this->db->delete('company', array('company_id' => $company_id));
}
Company Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('Company_model','company_model');
$this->load->library('session');
}
function index(){
$data['companies'] = $this->company_model->get_company();
$this->load->view('company_list_view',$data);
}
// add new company
function add_new(){
$data['subholding'] = $this->company_model->get_subholding()->result();
$this->load->view('add_company_view', $data);
}
// get sub category by category_id
function get_director(){
$subholding_id = $this->input->post('id',TRUE);
$data = $this->company_model->get_director($subholding_id)->result();
echo json_encode($data);
}
//save company to database
function save_company(){
$company_name = $this->input->post('company_name',TRUE);
$subholding_id = $this->input->post('subholding',TRUE);
$director_id = $this->input->post('director',TRUE);
$ceo_name = $this->input->post('ceo_name',TRUE);
$this->company_model->save_company($company_name,$subholding_id,$director_id,$ceo_name);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Saved</div>');
redirect('company');
}
function get_edit(){
$company_id = $this->uri->segment(3);
$data['company_id'] = $company_id;
$data['subholding'] = $this->company_model->get_subholding()->result();
$get_data = $this->company_model->get_company_by_id($company_id);
if($get_data->num_rows() > 0){
$row = $get_data->row_array();
$data['director_id'] = $row['company_director_id'];
}
$this->load->view('edit_company_view',$data);
}
function get_data_edit(){
$company_id = $this->input->post('company_id',TRUE);
$data = $this->company_model->get_company_by_id($company_id)->result();
echo json_encode($data);
}
//update company to database
function update_company(){
$company_id = $this->input->post('company_id',TRUE);
$company_name = $this->input->post('company_name',TRUE);
$subholding_id = $this->input->post('subholding',TRUE);
$director_id = $this->input->post('director',TRUE);
$ceo_name = $this->input->post('ceo_name',TRUE);
$this->company_model-
>update_company($company_id,$company_name,$subholding_id,$director_id,$ceo_name);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Updated</div>');
redirect('company');
}
//Delete Company from Database
function delete(){
$company_id = $this->uri->segment(3);
$this->company_model->delete_company($company_id);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Deleted</div>');
redirect('company');
}
Edit Company View
<!DOCTYPE html>
<html>
<head>
<title>Edit Company</title>
<link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row justify-content-md-center">
<div class="col col-lg-6">
<h3>Edit Company:</h3>
<form action="<?php echo site_url('company/update_company');?>" method="post">
<div class="form-group">
<label>Company</label>
<input type="text" class="form-control" name="company_name" placeholder="Company
Name" required>
</div>
<div class="form-group">
<label>Subholding</label>
<select class="form-control subholding" name="subholding" required>
<option value="">No Selected</option>
<?php foreach($subholding as $row):?>
<option value="<?php echo $row->subholding_id;?>"><?php echo $row->subholding_name;?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Director</label>
<select class="form-control director" name="director" required>
<option value="">No Selected</option>
</select>
</div>
<div class="form-group">
<label>CEO</label>
<input type="text" class="form-control" name="ceo_name" placeholder="CEO Name"
required>
</div>
<input type="hidden" name="company_id" value="<?php echo $company_id?>" required>
<button class="btn btn-success" type="submit">Update Company</button>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
<script type="text/javascript">
$(document).ready(function(){
//call function get data edit
get_data_edit();
$('.subhodling').change(function(){
var id=$(this).val();
var director_id = "<?php echo $director_id;?>";
$.ajax({
url : "<?php echo site_url('company/get_director_id');?>",
method : "POST",
data : {id: id},
async : true,
dataType : 'json',
success: function(data){
$('select[name="director"]').empty();
$.each(data, function(key, value) {
if(director_id==value.director_id){
$('select[name="director"]').append('<option value="'+ value.director_id
+'" selected>'+ value.director_name +'</option>').trigger('change');
}else{
$('select[name="director"]').append('<option value="'+ value.director_id
+'">'+ value.director_name +'</option>');
}
});
}
});
return false;
});
//load data for edit
function get_data_edit(){
var company_id = $('[name="company_id"]').val();
$.ajax({
url : "<?php echo site_url('company/get_data_edit');?>",
method : "POST",
data :{company_id :company_id},
async : true,
dataType : 'json',
success : function(data){
$.each(data, function(i, item){
$('[name="company_name"]').val(data[i].company_name);
$('[name="subholding"]').val(data[i].company_subholding_id).trigger('change');
$('[name="director"]').val(data[i].company_director_id).trigger('change');
$('[name="ceo_name"]').val(data[i].ceo_name);
});
}
});
}
});
</script>
</body>
</html>
In your view, the select field for the Director is:
<select class="form-control director" name="directore" required>
Everywhere else in your view, controller and model, you're expecting a variable named director which is not really there, so when you use $this->input->post('director') you're actually getting a NULL value which explains why your updates are not working.
A simple fix would be to change your select to
<select class="form-control director" name="director" required>
and you should be ok

Upload Image to Database using Ajax and Codeigniter

I have a CRUD with ajax working , but i want to implement a file upload to it.
Everything works fine except the image upload , the image is the only thing that is not saving on database and folder , all the other data are saving.
This is my CRUD Controller(just the add part) where I've implemented the upload code (dados)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('dados_model');
$this->load->database();
}
public function index()
{
$data['dados']=$this->dados_model->get_all_dados();
$this->load->view('dados_view',$data);
}
public function dados_add()
{
$config = array(
'upload_path' => "./assets/uploads",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
);
$this->load->library('upload',$config);
$this->upload->do_upload('userfile');
$data2=array('upload_data' => $this->upload->data());
$data = array(
'Name' => $this->input->post('Name'),
'City' => $this->input->post('City'),
'address' => $this->input->post('address'),
'lastname' => $this->input->post('lastname'),
'Image' =>$data2['upload_data']['file_name']
);
$this->dados_model->dados_add($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->dados_model->get_by_id($id);
echo json_encode($data);
}
And this is my Model, I use it to store the data on the database(dados_model)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class dados_model extends CI_Model
{
var $table = 'dados';
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_dados()
{
$this->db->from('dados');
$query=$this->db->get();
return $query->result();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('ID',$id);
$query = $this->db->get();
return $query->row();
}
public function dados_add($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
This is my Ajax code to save
<script type="text/javascript">
$(document).ready( function () {
$('#table_id').DataTable();
} );
var save_method; //for save method string
var table;
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal
title
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data:$('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
and this is my Modal Form to save
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">dados Form</h3>
</div>
<div class="modal-body form">
<form action="#" method="post" enctype="multipart/form-data" id="form"
class="form-horizontal">
<input type="hidden" value="" name="ID"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Name</label>
<div class="col-md-9">
<input name="Name" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">City</label>
<div class="col-md-9">
<input name="City" placeholder="City" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<input name="Address" placeholder=""
class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input name="lastname" placeholder="" class="form-control"
type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile" placeholder="" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
<input type ="submit" name="submit" value="Salvar" id="btnSave "
onclick="save()" class="btn btn-primary" />
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
</body>
</html>
First, try adding a '/' to the end of 'upload_path' => "./assets/uploads" in your code. This way you have a complete path for the image to go to.
Also, just so your aware, uploading an image like this will save the image on your server in the path provided. This means you need to store the file name in the database.So Make sure that 'Image' =>$data2['upload_data']['file_name'] actually has the correct file name so that when you query that file name from the db you can then find it at ./assets/uploads/filename on your server.
Additionally,
What do you get if you var_dump($data2['upload_data']['file_name'])?
What do you get if you var_dump($this->upload->display_errors()) after calling do_upload?
after searching some ajax codes, this is what worked for me
I changed my ajax function save to this
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('dados/dados_add')?>";
}
else
{
url = "<?php echo site_url('dados/dados_update')?>";
}
$('#form').submit(function(e)
{
$.ajax({
url : url,
type: "POST",
data: new FormData(this),
dataType: "JSON",
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
});
}

Codeigniter form validation return false on ajax request

Before I start, sorry for my English. i am developing a website using CI on Backend. And i want to make a registration system without refreshing the page. If i try with post form submit i got no error and everything went good. but when I try using with ajax request, I can't use form validation because form validation return false and validation_errors is empty. if I disable form validation, ajax request works well. here is my controller and ajax request. Please help me.
User.php (My Controller)
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
$data = json_encode(array('status'=> false,'info'=>validation_errors()));
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
$data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
} else {
$data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
}
}else{
$data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
}
}
echo $data;
}
}
And here is my ajax request in js
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: url + 'User/register', //url is correct i tested without form validation
data: $('#register-form').serialize(),
dataType: "json",
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
edit: and here is my form:
<!-- Register Form -->
<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
<div class="md-form">
<input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="name_kyt" >Name</label>
</div>
<div class="md-form">
<input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="surname_kyt" >Surname</label>
</div>
<div class="md-form">
<input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="username_kyt" > Username </label>
</div>
<div class="md-form">
<input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="email_kyt" >Email</label>
</div>
<div class="md-form">
<input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="password_kyt" >Password</label>
</div>
<div class="md-form">
<input type="password" id="password_confirm" name="password_onay" class="form-control">
<label for="password_confirm" >Password Confirm</label>
</div>
<div class="form-group text-center">
<div class="row">
<div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
<input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
<p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>
</div>
</div>
</div>
<!-- End of Register Form -->
<?php echo form_close(); ?>
Please refer below example to validate a form in CodeIgniter using ajax call.
1. ajax code.
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
var formData = $("#register-form").serialize();
$.ajax({
type: 'get',
url: url + 'User/register',
data: formData,
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
2. Controller code :
Load form_validation library and form helper
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
public function register(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
} else {
echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
}
}else{
echo $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
}
}
}
}
I have solved this problem. Form validation only works with post method. If you use get method it won't work.

regenerate csrf token after ajax request

How to regenerate a token's input after ajax request, so i don't need to reload the page,
here's my php code to generate a token
<?php
class Token {
public static function generate() {
return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
public static function check($token){
if(isset($_SESSION['token']) && $token === $_SESSION['token']){
unset($_SESSION['token']);
return true;
}
return false;
}
}
?>
and here's my jQuery code to send an ajax request
function load() {
$('#load-data').load('process/karyawan/load.php');
}
function insert(){
$('form').submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: 'process/karyawan/insert.php',
data: form.serialize(),
success: function(result){
load();
}
}
});
});
}
and here's my form
<form action="" method="post">
<div class="kiri">
<div class="inp">
<input type="text" name="nama_karyawan" placeholder="Nama Karyawan" class="form-control nama_karyawan">
</div>
<div class="inp">
<textarea class="form-control" name="alamat_karyawan" rows="5" placeholder="Alamat Karyawan"></textarea>
</div>
</div>
<div class="kanan">
<div class="inp">
<input type="password" name="password" placeholder="Password" class="form-control">
</div>
<div class="inp">
<input type="text" name="telepon_karyawan" class="form-control" placeholder="Telepon Karyawan">
</div>
<div class="inp">
<input name="akses" class="form-control" value="Admin" readonly>
<div class="error-msg err05"></div>
</div>
<div class="inp">
<input type="submit" name="insert" value="Simpan" class="btn btn-success col-sm-12">
<input type="hidden" name="token" value="<?=Token::generate();?>">
</div>
</div>
</form>
And here's my load.php file
<?php
session_start();
require_once('../../classes/Config.php');
require_once('../../classes/Database.php');
require_once('../../classes/Query.php');
require_once '../../classes/ErrorHandler.php';
require_once '../../classes/Validator.php';
require_once '../../classes/Token.php';
$connection = new Database($host, $username, $password, $database);
$main = new Query($connection);
$table = 'karyawan';
$selectData = $main->select($table);
while($fetchData = $selectData->fetch_object()){
if(#$_SESSION['owner']){
$delete = '<i class="fa fa-trash"></i>';
$button = '<td class="text-center">'.$delete.'</td>';
}else{
$button = null;
}
echo '<tr>
<td class="text-center">'.$fetchData->id_karyawan.'</td>
<td class="text-center">'.$fetchData->nama_karyawan.'</td>
<td class="text-center">'.$fetchData->alamat_karyawan.'</td>
<td class="text-center">'.$fetchData->telepon_karyawan.'</td>
<td class="text-center">'.$fetchData->akses.'</td>
'.$button.'
</tr>';
}
?>
For first request the code is running well, but for the second request I think it wouldn't be running well anymore because I've unset the token.. can someone give me an advice to regenerate a token after ajax request ? thank you
Because you're unset your token, the next validation will fail. You have to regenerate a new one after check and update your HTML token' field.
First, in your JS insert(), add "json" datatype.
Then, in your success function, update the field.
function insert(){
$('form').submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: 'process/karyawan/insert.php',
data: form.serialize(),
dataType: "json", // NEW
success: function(result){
$("input[name=token]").val(result.token); // NEW
load();
}
}
});
});
}
And in your update.php :
session_start();
// check and to stuff...
// then
$new_token = Token::generate(); // generate a new token
echo json_encode(['token' => $new_token]); // send to JS
die;

invalid-request-cookie using ajax validation recaptcha on codeigniter

thanks for reading my question, i have some issues trying to validate a recaptcha, with codeigniter with jquery ajax method, i always get invalid-requste-cookie, here is part of my code
Part of "welcome" controller
public function anunciese()
{
$data['recaptcha_html'] = $this->recaptcha->recaptcha_get_html();
$data['main_content'] = 'welcome/anunciese';
$this->load->view('includes/'.$this->config->config["tema"].'/template' , $data);
}
public function validar_recaptcha()
{
$this->recaptcha->recaptcha_check_answer(
$_SERVER['REMOTE_ADDR'],
$this->input->post('recaptcha_challenge_field'),
$this->input->post('recaptcha_response_field'));
if ($this->recaptcha->getIsValid() == false)
{
$datos['success'] = false;
$datos['titulo'] = "ERROR";
$datos['mensaje'] = $error = $this->recaptcha->getError();
}
else
{
$datos['success'] = true;
$datos['titulo'] = "";
$datos['mensaje'] = "";
}
echo json_encode($datos);
}
Here is the view (part of It)
<form class="form-horizontal" method="post">
<fieldset>
<div class="form-group">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input class="form-control" id="inputEmail" placeholder="Email" type="text">
</div>
</div>
<div class="form-group">
<label for="inputNombre" class="col-lg-2 control-label">Nombre</label>
<div class="col-lg-10">
<input class="form-control" id="inputNombre" placeholder="Nombre" type="text">
</div>
</div>
<div class="form-group">
<?php echo $recaptcha_html; ?>
</div>
<div class="form-group">
<input type="button" class="btn btn-primary" value="Suscribirme Gratis" onClick="SalvarProspecto()" />
</div>
And finally my js code
function ValidarRecaptcha()
{
var phpencode = true;
var urlx = base_url + 'welcome/validar_recaptcha';
$.ajax({
type: "POST",
url: urlx,
data: {},
async: false,
success: function (data) {
if (phpencode == true) {
data = $.parseJSON(data);
}
console.log(data) //Solo para propositos de debug
if (data.success) {
return true;
} else {
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failed " + urlx);
alert(xhr.responseText);
alert(thrownError);
}
});
}
I am using this library https://github.com/Cnordbo/RECaptcha-for-Codeigniter
Any help would be appreciated
Just made it without ajax requests, and making it a basic form, with the form helper, and the codeigniter documentation here, like that example https://github.com/Cnordbo/RECaptcha-for-Codeigniter

Categories