Using Ajax on CRUD in Codeigniter

Hi all i'm trying to doing C.R.U.D on codeigniter with Ajax but i don't have any experience in Ajax.

So first i have done with add function. Its work but i want after add or edit to refresh table.

This is my modal which is for update :

      <!-- Update  Interview-->
    <div class="modal fade" id="interview" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
      <div class="modal-dialog">
    <div id="form-content">

    <div class="modal-content">

          <div class="modal-header">
        <button type="button" class="close"  data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
        <h4 class="modal-title custom_align" id="Heading">Edit Your Detail</h4>
      </div>
          <div class="modal-body">
                 <?php
                    echo form_open('vacancy/interview/'. $row['id'], array("class" => "no-error-margin interview",  "name" => "interview" , "id" => "edit-stage"));
                    ?>  


        <div class="form-group">
        <label class="control-label">Type:</label>
            <select id="classinput" tabindex="1" name="priority" class="form-control required">
                  <option value="A">First Interview</option>
                  <option value="B">Second Interview</option>
                  <option value="B">Final Interview</option>
            </select>
         </div>    
        <div class="date-form">

        <div class="control-group">
        <label class="control-label" style="margin: 0 30%;padding: 7px;">When The Interview Will Be?</label>

    <div class="container">
    <div class="row">
        <div class='col-sm-6 col-md-offset-3'>
            <div class="form-group">
                <div class='input-group date' id='datetimepicker1'>
                    <input type='text' class="form-control" />
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
        </div>
        </div>

      </div>

          <div class="modal-footer ">
        <button id="uin" type="submit" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
      </div>
        </div>
    <!-- /.modal-content --> 
        </form>

  </div>

      <!-- /.modal-dialog --> 
    </div>   
    </div>   

i try with following Ajax code for update:

    $("#uin").click(function(){
    $.ajax({
        type: "POST",
        url: "vacancy/interview/<?= $row['id'] ?>", //process
        data: $('form.interview').serialize(),
        success: function(msg){
            alert("Succeess");
            $("#form-content").modal('hide'); //hide popup  
        },
        error: function(){
            alert("failure");
        }
    });
});

But getting Codeigniter Error The action you have requested is not allowed.

Controller function:

        public function interview($i) 

    {
        $type=$this->input->post();
        $this->vacancies->update_interview($type, array("id" => $id));             
    }

and Model

    public function update_interview($i) 
{
    $this->db->insert("interviews", $i);
}

Can you tell me where i'm wrong?

Answers


For the error

The action you have requested is not allowed

you have CSRF protection enabled $config['csrf_protection'] = TRUE;.

Try disabling this in your config.php and see if it works. In general you should use CSRF for security purposes anyway. To implement this correctly you should add the csrf token to your ajax post data so that Codeigniter can see and validate each form and each ajax request you do.

A simple example of adding CSRF to your AJAX is the following:

var cct = $.cookie('<?php echo $this->config->item("csrf_cookie_name"); ?>');
var request = $.ajax({
            url: "/action/doaction",
            type: "POST",
            data: { '<?php echo $this->security->get_csrf_token_name(); ?>': cct }
        });

Crud operation with Import, Export Using Ajax.

Create a file view.php

<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery-3.2.1.js"></script>
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery.validate.min.js"></script>

<link href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.css" rel="stylesheet" type="text/css" />

<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?=$this->config->item('css_path')?>bootstrap.min.css"> 

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.5.0/css/fileinput.css" rel="stylesheet" type="text/css" />

<html>
<head>
<div id="myDropdown" class="dropdown-content">
    <a href="<?php echo base_url('User_management/add') ?>">Registration Form</a>
    <a href="<?php echo base_url('User_management/index') ?>">User Listing</a>
  </div>
    <div align="center"><h3>Registration Form</h3></div>
</head>
<body>
    <form id="signup_form" method="post" action="" enctype="multipart/form-data" >

        <table border="1" align="center" width="450">
            <tr>
                <td>First Name</td>
                <td>
                    <input type="text" name="first_name" id="first_name" value="<?php echo !empty($editRecord[0]->first_name) ? $editRecord[0]->first_name :'' ?>">
                </td>
            </tr>

            <tr>
                <td>Last Name</td>
                <td>
                    <input type="text" name="last_name" id="last_name" value="<?php echo !empty($editRecord[0]->last_name) ? $editRecord[0]->last_name :'' ?>">
                </td>
            </tr>

            <tr>
            <?php echo validation_errors(); ?>
                <td>Email</td>
                <td>
                    <input type="email" name="email" id="email" onblur="check_email(this.value);" value="<?php echo !empty($editRecord[0]->email) ? $editRecord[0]->email :'' ?>">
                     <label id="message"></label>
                </td>
            </tr>

            <tr>
                <td>Mobile Number</td>
                <td>
                    <input type="text" name="mobile_no" id="mobile_no" onkeypress="return isNumber(event)" data-range='[1,9999999999]' maxlength="15" value="<?php echo !empty($editRecord[0]->mobile_no) ? $editRecord[0]->mobile_no :'' ?>">
                </td>
            </tr>

           <tr>

            <tr>
                <td>Gender</td>
                <td>
                    <select name="gender" id="gender">
                        <option value="">Select Gender</option>
                        <option value="0" <?php if(!empty($editRecord[0]->gender) && $editRecord[0]->gender == 0) echo "selected" ;?>>male</option>
                        <option value="1" <?php if(!empty($editRecord[0]->gender) && $editRecord[0]->gender == 1) echo "selected"; ?>>Female</option>
                    </select>
                </td>
            </tr>

            <td>Address</td>
                <td>                   
                    <textarea name="address" id="address"><?php echo !empty($editRecord[0]->address) ? $editRecord[0]->address :'' ?></textarea>
                </td>
            </tr>
            <?php if(empty($editRecord))
            {
                ?>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" name="password" id="password" value="">
                </td>
            </tr>

            <tr>
                <td>Confirm Password</td>
                <td>
                    <input type="password" name="cpassword" id="cpassword" value="">
                </td>
            </tr>
            <?php 
            }
            ?>

            <tr>
                <td>Image</td>
                <div class="fileinput fileinput-new" data-provides="fileinput">
                    <td class="fileinput-preview thumbnail" data-trigger="fileinput" style = "width: 20px; height: 20px;"><img src="<?php echo base_url() ?>/uploads/<?php echo !empty($editRecord[0]->image) ? set_value("title", $editRecord[0]->image) : set_value("title","images.jpg"); ?>">

                        <!-- <input type="file" name="file" id="file" value="<?php echo !empty($editRecordRecord[0]->file) ? $editRecordRecord[0]->file :'' ?>"> -->
                        <input type="file" name="user_files" id="user_files" value="<?php echo !empty($editRecord[0]->image) ? set_value("title", $editRecord[0]->image) : set_value("title","images.jpg"); ?>" > 
                    </td>
                </div>
                <input type="hidden" name="picture_name" value="<?php echo isset($editRecord[0]->image) ? set_value("title", $editRecord[0]->image) : set_value("title",""); ?>" >
            </tr>

            <tr collspan="2">
                <td align="center">
                    <input type="submit" name="submit" value="submit">
                </td>
            </tr>

        </table>
        <input type="hidden" name="id" id="id" value="<?= !empty($editRecord[0]->id)?$editRecord[0]->id:'';?>" >
    </form>

</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.5.0/js/fileinput.js" type="text/javascript"></script>  
<script type="text/javascript">
    $("#signup_form").validate({
        onkeyup: false,
        rules:{
            first_name: {
                required: true
            },
            last_name: {
                required: true
            },
            email:{
                required: true,
                email: true,
            },
            mobile_no:{
                required:true,
                minlength:10,
                maxlength:15
            },
            password:{
                required:true,
                minlength:6,
                normalizer: function(value){
                    return $.trim(value);
                },
                password_check: true
            },
            cpassword:{
                required:true,
                normalizer: function(value){
                    return $.trim(value);
                },
                equalTo: "#password",
            },
        },
        messages:{
            first_name:{
                required: "First Name cannot be blank.",
            },
            last_name:{
                required: "Last Name cannot be blank.",
            },
            email:{
                required: "Email cannot be blank.",
            },
            mobile_no:{
                required: "Mobile number cannot be blank",
                minlength: "Please enter minimum 10 digit number.",
                maxlength: "Contact Number not allow more then 15 digit."
            },
            password:{
                required: "Password cannot be blank.",
                minlength: "Password should be at least 6 character long."
            },
            cpassword:{
                required: "Confirm Password cannot be blank.",
                equalTo: "Password and Confirm Password must be same." 
            },
        },
    });

    jQuery.validator.addMethod('password_check', function(value,element)
    {
        var pattern = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{6,}$/);
        //
        if(pattern.test(value))
        {
            return true;
        }else{
           return false;
        }
    },"Password should be 6 character long, one special character, one uppercase, one lowercase letter and one digit.");

    function isNumber(evt)
    {
         evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 32 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
    }

    $('#signup_form').submit(function(e) {

        var id = $('#id').val();
        e.preventDefault();

        if(id == '')
        {
            url = "<?php echo base_url('user_management/insert_record/');?>" + $("#id").val();
            $.ajax({
                url:url,
                type:"post",
                data:new FormData(this),
                processData:false,
                contentType:false,
                cache:false,
                async:false,
                success: function(data){
                    if (data == 1) {    
                    //setTimeout(function(){document.location.href = "index"},500);                
                    toastr.success('Recored Added Successfully.', 'Success Alert', {timeOut: 5000});
                    }
                    $('#signup_form').trigger("reset");
                },
                error: function() { alert("Error posting feed."); }
            });
        }
        else
        {           
            url = "<?php echo base_url('user_management/update_record/');?>" + $("#id").val();
            $.ajax({
                url:url,
                type:"post",
                data:new FormData(this),
                processData:false,
                contentType:false,
                cache:false,
                async:false,
                success: function(data){
                    if (data == 1) {                    
                        toastr.success('Recored Updated Successfully.', 'Success Alert', {timeOut: 5000});
                        setTimeout(function(){document.location.href = "index"},5000);
                    }
                    //$('#signup_form').trigger("reset");
                },
                error: function() { alert("Error posting feed."); }
            });
        }

    });

    function check_email(email)
    {
       var id = $('#id').val();
        $.ajax({
            type: "POST",
            url: '<?php echo base_url(); ?>'+"user_management/check_email",
            dataType: 'json',
            async: false,
            data: {'email':email,'id':id},

            success: function(data){
            if(data == '1')
            {$('#email').focus();
             $('#submit').attr('disabled','disabled');

              $.confirm({
                        title: 'Alert',
                        content: " <strong> This email already existing. Please select other email. "+"<strong></strong>",
                        buttons: {'ok'  : {'class'  : 'btn_center alert_ok',
                        action: function(){
                        $('#email').focus();
                        $('#email').val('');
                        $('#submit').removeAttr('disabled');

                      }}}});
            }            
            }
          });
        return false;
    }

function readURL(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#profile').attr('src', e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
}
}
$("#user_files").change(function(){
    readURL(this);
});
</script>

I user jQuery validation for validate the fields.

Create a file to show details list.php

<link rel="stylesheet" type="text/css" href="<?=$this->config->item('css_path')?>bootstrap.min.css"> 
<script type="text/javascript" src="<?=$this->config->item('js_path')?>jquery-3.2.1.js"></script>
<html>
<body>
<table border="2" align="center">

    <tr>
        <td width="30">#</td>
        <td>Name</td>
        <td>Email</td>
        <td>Mobile No.</td>
        <td>Gender</td>
        <td>Address</td>
        <td>Image</td>
        <td>Action</td>

    </tr>

    <?php 
    foreach($user_details as $user)
    {
        ?>
        <tr>
            <td><?php echo $user->id;?></td>
            <td><?php echo ucwords($user->name);?></td>
            <td><?php echo $user->email;?></td>
            <td><?php echo $user->mobile_no;?></td>
            <td><?php 
                if($user->gender == 0)
                { 
                    echo "Male";
                }elseif ($user->gender == 1) {
                    echo "Female";
                }
                ?>
            </td>
            <td><?php echo $user->address;?></td>
            <td><img style="width: 50px;height: 40px;" src="<?php echo base_url('uploads/'. $user->image);?>" /></td>

            <td>
                <a href="<?php echo base_url('User_management/edit_record/')?><?php echo $user->id?>">Edit</a>
                <span class='delete' id='del_<?php echo $user->id; ?>'>Delete</span>
            </td>
        </tr>

        <?php
    }
   ?>   
   <tr>
    <td colspan="2"><a href="<?php echo base_url('User_management/add')?>">Add new</a></td>
    <td colspan="1">
        <div class="col-md-3">
            <form action="<?php echo site_url("User_management/ExportCSV");?>" method="post" enctype="multipart/form-data" id="exportFrm">    <input type="submit" class="btn btn-success howler" name="exportSubmit" value="Export">
            </form>
        </div>
    </td>
    <td colspan="2">                       
        <div class="col-md-2 pull-right">
            <a href="javascript:void(0);" onclick="$('#importFrm').slideToggle();">Import Users</a>
        </div>
    </td>
    <td colspan="3">                       
        <form action="<?php echo site_url("User_management/upload_file");?>" method="post" enctype="multipart/form-data" id="importFrm">
            <input type="file" name="file" />
            <input type="submit" class="btn btn-primary" name="importSubmit" value="Import">
        </form>
    </td>
   </tr>
   </table>
   </body>
   </html>

<script type="text/javascript">

    $(document).ready(function(){

        $('.delete').click(function(){
        var el = this;
        var id = this.id;
        var splitid = id.split("_");

         // Delete id
        var deleteid = splitid[1];

         // AJAX Request
        $.ajax({
            url: "<?php echo base_url('user_management/delete/');?>",
            type: 'POST',
            data: { id:deleteid },
            success: function(response){

               // Removing row from HTML Table
                $(el).closest('tr').css('background','tomato');
                $(el).closest('tr').fadeOut(800, function(){ 
                $(this).remove();
                    });
                }
            });

        });
    });
</script>
<style type="text/css">
    .panel-heading a{float: right;}
    #importFrm{margin-bottom: 20px;display: none;}
    #importFrm input[type=file] {display: inline;}
</style>

now create model Common_model.php

<?php

Class Common_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    function encrypt_script($string)
    {
        $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
        $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $string, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
           return( $qEncoded );
    }

    function decrypt_script($string)
    {
        $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
        $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
           return( $qDecoded );
    }

    function insert($table,$data)
    {
        $this->db->insert($table,$data);
        return $this->db->insert_id();
    }

    function get_users()
    {
        $this->db->select('id, CONCAT(`first_name`," ", `last_name`) AS `name` ,email,mobile_no,gender,address,image');
        $result = $this->db->get('user_master');
        return $result->result();
    }

    public function get_user_detail($id){
        $this->db->select('*');
        $this->db->where('id',$id);
        $result = $this->db->get('user_master');
        return $result->result();
    }

    public function update($table,$data,$where)
    {
        if(!empty($where))
            $this->db->where($where);
            $this->db->update($table, $data);
    }

    public function delete($table, $where)
    {

        $this->db->where($where);
        $this->db->delete($table);
    }

    public function select_where($table,$where)
    {
        $rec=$this->db->get_where($table,$where);
        return $rec->result();
    }
}
?>

Now create controller user_management_control.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

Class User_management extends CI_Controller
{
    public  function __construct()
    {
        parent::__construct();
        $this->load->model('Common_model');
    }

    public function index()
    {
        $data['user_details'] = $this->Common_model->get_users();
        $this->load->view('user/list',$data);
    }

    public function add()
    {
        $this->load->view('user/add');
    }

    public function insert_record()
    {

        $config['upload_path']  = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('user_files'))
          {
             $photo.= $data['image'] = $this->input->post('picture_name');

          }
        else
          {           
              $data = array('upload_data' => $this->upload->data());
              global $photo ;
              $photo .= $data['upload_data']['file_name'];
          }
        $this->load->library('form_validation');

        if($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $this->form_validation->set_rules('first_name','First Name','trim|required');
            $this->form_validation->set_rules('last_name','Last Name','trim|required');
            $this->form_validation->set_rules('email','Email','trim|required|valid_email');
            $this->form_validation->set_rules('mobile_no','Mobile Number','trim|required');
            $this->form_validation->set_rules('password','Password','trim|required|matches[cpassword]');
            $this->form_validation->set_rules('cpassword','Confirm Password','trim|required');

            if($this->form_validation->run() == FALSE)
            {
                $this->load->view('user/add');
            }
            else
            {
                $post_array = $this->input->post();

                $data = array(
                    'first_name' => $post_array['first_name'],
                    'last_name' => $post_array['last_name'],
                    'email'      => strtolower(trim($post_array['email'])),
                    'mobile_no' => $post_array['mobile_no'],
                    'gender' => $post_array['gender'],
                    'address' => $post_array['address'],
                    'password' => $this->Common_model->encrypt_script($post_array['password']),
                    'status' => 0,
                    'image'=>$photo,
                    'inserted_date' => date('Y-m-d H:i:s')
                );

                $inser_data  = $this->Common_model->insert('user_master',$data);

                if(!empty($inser_data))
                {
                   echo '1';
                }
                else{

                    echo '0';
                }

            }
        }

    }

   public function check_email()
    {
        $id = $this->input->post('id');
        $email=$this->input->post('email');

        $exist_email= $this->Common_model->select_where('user_master',array('email'=>$email));

        if(!empty($exist_email))
        {
            if($exist_email[0]->id == $id)
            {
                echo '0';
            }
            else
            {
                echo '1';
            }
        }
        else
        {
            echo '0';
        }
    }

    public function edit_record()
    {

        $id = $this->uri->segment(3);
        $result = $this->Common_model->get_user_detail($id);
        if(empty($result))
        {
            redirect('user_management/');
        }
        $data['editRecord'] = $result;
        $this->load->view('user/add',$data);

    }

    public function update_record()
    {
        if(!empty($_FILES['user_files']['name']))
        {
            $config['upload_path']  = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png';
            $this->load->library('upload', $config);

            $this->upload->do_upload('user_files');
            $data['image'] = $this->upload->data('file_name');

        }
        else
        {
            $data['image'] = $post_array['picture_name'];
        }

        $this->load->library('form_validation');

        if($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $this->form_validation->set_rules('first_name','First Name','trim|required');
            $this->form_validation->set_rules('last_name','Last Name','trim|required');
            $this->form_validation->set_rules('email','Email','trim|required|valid_email');
            $this->form_validation->set_rules('mobile','Mobile Number','trim|required');

            $post_array = $this->input->post();
            $cdata['id'] = $post_array['id'];

            if(!empty($cdata['id'])){
                $data = array(
                    'first_name' => $post_array['first_name'],
                    'last_name' => $post_array['last_name'],
                    'email'      => strtolower(trim($post_array['email'])),
                    'mobile_no' => $post_array['mobile_no'],
                    'gender' => $post_array['gender'],
                    'address' => $post_array['address'],
                    'image' => $data['image'],
                    'status' => 0,
                    'modified_date' => date('Y-m-d H:i:s')
                );
//echo'<pre>';print_r($data);echo'<pre>';
                $this->Common_model->update('user_master',$data,array('id' =>$cdata['id']));  
                echo '1';
            }
            else{

                echo '0';
            }

        }
    }

    public function delete()
    {
        $id = $_POST["id"];

        if(!empty($id))
        {
            $this->Common_model->delete('user_master',array('id'=>$id));
            echo '1';
        }else{
            echo '0';
        }
    }

    public function upload_file()
    {
        $csvMimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes))
        {
            if(is_uploaded_file($_FILES['file']['tmp_name'])){

                //open uploaded csv file with read only mode
                $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                // skip first line
                // if your csv file have no heading, just comment the next line
                fgetcsv($csvFile);

                //parse data from csv file line by line
                while(($line = fgetcsv($csvFile)) !== FALSE){
                    //check whether member already exists in database with same email
                    $result = $this->db->get_where("user_master", array("email"=>$line[2]))->result();

                    if(count($result) > 0){
                        //update user_master data
                        $this->db->update("user_master", array("first_name"=>$line[0], "last_name"=>$line[1], "mobile_no"=>$line[3], "gender"=>$line[4],"address"=>$line[5]), array("email"=>$line[2]));
                    }else{
                        //insert user_master data into database
                        $this->db->insert("user_master", array("first_name"=>$line[0], "last_name"=>$line[1], "email"=>$line[2], "mobile_no"=>$line[3], "gender"=>$line[4],"address"=>$line[5]));
                    }
                }

                //close opened csv file
                fclose($csvFile);

                $qstring["status"] = 'Success';
            }else{
                $qstring["status"] = 'Error';
            }
        }else{
            $qstring["status"] = 'Invalid file';
        }

            redirect('user_management');
    }

    public function ExportCSV()
    {
        $this->load->dbutil();
        $this->load->helper('download');
        $delimiter = ",";
        $newline = "\r\n";
        $filename = "user.csv";
        $query = "SELECT * FROM user_master WHERE 1";
        $result = $this->db->query($query);
        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
        force_download($filename, $data);
    }
}
?>

Need Your Help

using shared preferences to store username and diplay username in fragment class

android login android-fragments fragment sharedpreferences

My application has a login screen which sends the user to a activity fragment, I would to know how to use shared preferences So That I can store the username the user inputs in the login activity, ...

The requested operation cannot be performed on a file with a user-mapped section open

windows dll

Whenever I tried to copy 4 files into my bin folder, after stopping the main service, I am getting an error with one file (TexteDll). The error is: