• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fetch and Update Data in same page CodeIgniter

#1
I got stuck in a a problem in which I need to update some info from database in the same page that is shown.

On this case I'm fetching some "global settings" from a website in an index page which comes with a form in it. Here is a picture of it just to make it more clear to understand what I mean.

[Image: s9Khw.png][Image: MiqKn.png]

As you can see I created the button and I made it possible to see the values from the database, the problem is that I can not figure it out how to update it from there. Can somebody suggest an idea?

Here is my controller:



PHP Code:
   public function index()
 
   {
        
 
       $this->form_validation->set_rules('website_favicon''Favicon''trim|required|min_length[4]');
 
       $this->form_validation->set_rules('website_logo''Logon''trim|required|min_length[4]');
 
       $this->form_validation->set_rules('website_name''Website Name''trim|required|min_length[4]');
 
       $this->form_validation->set_rules('website_credits''Credits''trim|required|min_length[4]');
 
       $this->form_validation->set_rules('website_credits_link''Credits Link''trim|required|min_length[4]');
 
       $this->form_validation->set_rules('website_copyright''Copyright''trim|required|min_length[4]');
        
        if(
$this->form_validation->run() == FALSE){
        
            
// Get Current Subject
            
$data['item'] = $this->Settings_model->get_website_data();
            
//Load View Into Template
            
$this->template->load('admin''default''settings/index'$data);
            
        } else {
            
            
// Create website settings
            
$data = array(
                
'website_favicon'    => $this->input->post('website_favicon'),
                
'website_logo'        => $this->input->post('website_logo'),
                
'website_name'        => $this->input->post('webiste_name'),
                
'website_credits'    => $this->input->post('website_credits'),
                
'website_credits_link'    => $this->input->post('website_credits_link'),
                
'website_copyright'    => $this->input->post('website_copyright'),
            );
            
 
           // Update User
 
           $this->Settings_model->update($id$data);

 
           // Activity Array
 
           $data = array(
 
               'resource_id' => $this->db->insert_id(),
 
               'type'        => 'website settings',
 
               'action'      => 'updated',
 
               'user_id'     => $this->session->userdata('user_id'),
 
               'message'     => 'User (' $data["username"] . ') updated the website settings'
 
           );

 
           // Add Activity  
 
           $this->Activity_model->add($data);

 
           //Create Message
 
           $this->session->set_flashdata('success''Website setting has been updated');

 
           //Redirect to Users
 
           redirect('admin/settings');
        
        } 
    } 

Here is my model:


PHP Code:
<?php

class Settings_model extends CI_MODEL
{

 
   function __construct()
 
   {
 
       parent::__construct();
 
       $this->table 'website_settings';
 
   }


 
   public function update($id$data)
 
   {
 
       $this->db->where('id'$id);
 
       $this->db->update($this->table$data);
 
   }


 
   public function get_website_data()
 
   {
 
       $this->db->select('*');
 
       $this->db->from($this->table);
 
       $this->db->where('id'1);
 
       $this->db->limit(1);

 
       $query $this->db->get();

 
       if ($query->num_rows() == 1) {
 
           return $query->row();
 
       } else {
 
           return false;
 
       }

 
   }



and here is my view:


Code:
<h2 class="page-header">Website Settings</h2>
<?php if($this->session->flashdata('success')) : ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Alert!</h4>
<?php echo $this->session->flashdata('success') ?></div>
<?php endif; ?>

<?php if($this->session->flashdata('error')) : ?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
<?php echo $this->session->flashdata('error') ?></div>
<?php endif; ?>

<?php echo validation_errors('<p class="alert alert-danger">'); ?>
<?php echo form_open('admin/settings/index/'.$item->id); ?>
   <!-- Website Favicon -->
   <div class="form-group">
       <?php echo form_label('Website Favicon', 'title'); ?>
       <?php
           $data = array(
               'name' => 'website_favicon',
               'id'    => 'website_favicon',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_favicon
           );
       ?>
       <?php echo form_input($data); ?>
   </div>
   <!-- Website Logo -->
   <div class="form-group">
       <?php echo form_label('Website Logo', 'website_logo'); ?>
       <?php
           $data = array(
               'name' => 'website_logo',
               'id'    => 'website_logo',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_logo
           );
       ?>
       <?php echo form_input($data); ?>
   </div>
   <!-- Website Name -->
   <div class="form-group">
       <?php echo form_label('Website Name', 'website_name'); ?>
       <?php
           $data = array(
               'name' => 'website_name',
               'id'    => 'website_name',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_name
           );
       ?>
       <?php echo form_input($data); ?>
   </div>
   <!-- Website Credits -->
   <div class="form-group">
       <?php echo form_label('Website Credits to', 'website_credits'); ?>
       <?php
           $data = array(
               'name' => 'website_credits',
               'id'    => 'website_credits',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_credits
           );
       ?>
       <?php echo form_input($data); ?>
   </div>
   <!-- Website Credits Link -->
   <div class="form-group">
       <?php echo form_label('Website Credits to Link', 'website_credits_link'); ?>
       <?php
           $data = array(
               'name' => 'website_credits_link',
               'id'    => 'website_credits_link',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_credits_link
           );
       ?>
       <?php echo form_input($data); ?>
   </div>
   <!-- Website Copyright -->
   <div class="form-group">
       <?php echo form_label('Copyrights', 'website_copyright'); ?>
       <?php
           $data = array(
               'name' => 'website_copyright',
               'id'    => 'website_copyright',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_copyright
           );
       ?>
       <?php echo form_input($data); ?>
   </div>
   <!-- Website First Ad -->
   <div class="form-group">
       <?php echo form_label('Ad One', 'website_first_ad'); ?>
       <?php
           $data = array(
               'name' => 'website_first_ad',
               'id'    => 'website_first_ad',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_first_ad
           );
       ?>
       <?php echo form_textarea($data); ?>
   </div>
   <!-- Website Second Ad -->
   <div class="form-group">
       <?php echo form_label('Ad Two', 'website_second_ad'); ?>
       <?php
           $data = array(
               'name' => 'website_second_ad',
               'id'    => 'website_second_ad',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_second_ad
           );
       ?>
       <?php echo form_textarea($data); ?>
   </div>
   <!-- Website Third Ad -->
   <div class="form-group">
       <?php echo form_label('Ad Three', 'website_third_ad'); ?>
       <?php
           $data = array(
               'name' => 'website_third_ad',
               'id'    => 'website_third_ad',
               'maxlength' => '100',
               'class'     => 'form-control',
               'value'     => $item->website_third_ad
           );
       ?>
       <?php echo form_textarea($data); ?>
   </div>

   <?php echo form_submit('mysubmit', 'Update Website', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
Thanks for helping.
Also any idea how can I use this globally in a template?
I do Front-End development most of the time 
Reply

#2
You would need JavaScript or jQuery to update on the same page without a refresh.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
(12-14-2017, 02:27 AM)kirasiris Wrote: I got stuck in a a problem in which I need to update some info from database in the same page that is shown.

On this case I'm fetching some "global settings" from a website in an index page which comes with a form in it. Here is a picture of it just to make it more clear to understand what I mean.

...

Thanks for helping.
Also any idea how can I use this globally in a template?

You can add an if statement to your controller (inside the "get_website_data" function) and you can check submit of any form field. Then you can put whole save data code inside of this if statement. I prefer to use form submit button for this. Because if you can check an input field and its value is empty, maybe you can't catch it in the controller. Like this:

Code:
if($this->input->post('submit_settings')){
// Saving data code
}

I hope this helps.
Reply

#4
Short answer: you need AJAX

Long answer: Since i cant see your full script (especially your javascript). and i never use  form helper yet. i cant guarantee this will work.

modify my script if this not work. i add comment to help you.
try this

PHP Code:
<?php echo form_close(); ?> //your last line
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
    $('form').submit(function(e){
        var formdata = $(this).serializeArray(); //serialize all your data in <form>
        
        //because ckeditor is create new dom, we cant get original textarea, so serializeArray cant catch them. so we need to push the value into formdata array
        //i assume you use ckeditor 4.x.x , 
        formdata.push({'name':'website_first_ad', 'value':CKEDITOR.instances.website_first_ad.getData()}); 
        formdata.push({'name':'website_second_ad', 'value':CKEDITOR.instances.website_second_ad.getData()}); 
        formdata.push({'name':'website_third_ad', 'value':CKEDITOR.instances.website_third_ad.getData()}); 
        var btn = $(this).find('input[name="mysubmit"]');
        var btnText = btn.val();
        $.ajax({
            url: '<?php echo site_url('admin/settings/index/'$item->id);?>', //change with your submit url, if im wrong
            type: 'post', //i hope your data is post, otherwise change it to get if you use GET
            data: formdata,
            dataType: 'json', //i recommend output as json not plain text
            beforeSend: function(){ //prevent double click when your script in process. and add styling on the button
                btn.prop('disabled', true).addClass('btn-warning').removeClass('btn-primary').val('wait');
            },
            success: function(d){
                if(d['status']=='success'){
                    alert(d['msg']);
                    btn.addClass('btn-success').removeClass('btn-warning').val('success');
                }else{
                    btn.addClass('btn-danger').removeClass('btn-warning').val('failed');
                    alert('Update data failer'); 
                    console.log(d); //for debug in console
                }
                setTimeout(function(){
                    btn.prop('disabled', false).addClass('btn-primary').removeClass('btn-success btn-danger').val(btnText);
                }, 2000);
            },
            error: function(d){
                btn.addClass('btn-danger').removeClass('btn-warning').val('error');
                alert('Something wrong happen'); 
                console.log(d.responseText); //for debug in console
                setTimeout(function(){
                    btn.prop('disabled', false).addClass('btn-primary').removeClass('btn-success btn-danger').val(btnText);
                }, 2000);
            }
        });
    });
});
</script> 

and your controller

PHP Code:
function index()
{
    ...
snippet...
    
//Create Message
    //$this->session->set_flashdata('success', 'Website setting has been updated'); comment this
    
$result = array('status'=>'success''msg'=>'Website setting has been updated');
    echo 
json_encode($result); //we throw response as json (javascript array)
    //Redirect to Users
    //redirect('admin/settings'); no need this anymore. you will not reload your page

Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.