softboxkid
softboxkid

Reputation: 908

Submit form via jquery modal to codeigniter controller

I had a problem on submitting the form thru ajax jquery. My problem is, how to submit the jquery modal form to the codeigniter controller without refresh the page? at the same time, if the submitted data contains an error from codeigniter controller (validation), how the jquery will show the error message?

here is my code

js script

$(function() {

// Dialog
$('#dialog').dialog({
    autoOpen: false,
    width: 380,
    height:300,
    buttons: {
        'Save': function() {

  function submitForm(){

  $.ajax({
  type : 'POST',
  url : 'http://localhost/hmvc/index.php/sysconfig/sysmenu/create',
  data : $('#menu_form').serialize(),
  success : function(data) {
      // Show OK message
      alert('ok');
  },
  error: function(error){
      // Show error message
      alert('error');
  }
});

return false;
}

        },
        'Cancel': function() {
            $(this).dialog("close");
        }
    } 
 }); 

// Dialog Link
$('#dialog_link').click(function(){
    $('#dialog').dialog('open');
    return false;
}); 


});

controller

function _validate()
{
    $config = array(

                array(
                'field'=>'sysmenu_name',
                'label'=>'menu name',
                'rules'=>'trim|max_length[30]|htmlspecialchars|required|xss_clean'
                ),

                array(
                'field'=>'sysmenu_link',
                'label'=>'hyperlink',
                'rules'=>'trim|max_length[100]|htmlspecialchars|required|xss_clean'
                ),

                array(
                'field'=>'sysmenu_sequence',
                'label'=>'sequence',
                'rules'=>'trim|max_length[2]|htmlspecialchars|required|xss_clean'
                )

              );

    $this->form_validation->set_rules($config);

    $this->form_validation->set_error_delimiters('<div class="error_msg">', '</div>');
}

function create()
{
  if($this->input->is_ajax_request())
  {
    $this->_validate();
    if($this->form_validation->run($this)==FALSE)
    {

           echo validation_errors();
    }


    } else {

        $menu_level = getValue_where('sysmenu_level',"sysmenu_id ='".$this->input->post('sysmenu_parent_id')."'",'base_sysmenu') + 1;

        $data = array(
                'sysmenu_name'=>$this->input->post('sysmenu_name'),
                'sysmenu_parent_id'=>$this->input->post('sysmenu_parent_id'),
                'sysmenu_link'=>$this->input->post('sysmenu_link'),
                'sysmenu_level'=>$menu_level,
                'sysmenu_sequence'=>$this->input->post('sysmenu_sequence')
                );

        $this->sysmenu_model->insert_menu($data);
        $this->index();
    }
}

view

<div id="dialog" title="<?php echo $this->lang->line('add_new_menu') ?>">
<div class="notice_msg"><?php echo $this->lang->line('compulsary'); ?></div><br />

<div class="errors"><!-- append the error message here --></div>

<?php echo form_open('','class=normal_form name=create_menu id=menu_form'); ?>
<label><?php echo $this->lang->line('menu_name'); ?></label><?php echo form_input('sysmenu_name'); ?>*<br />
<label><?php echo $this->lang->line('parent_menu'); ?></label><?php //echo form_input('sysmenu_parent_id'); ?><?php echo form_dropdown('sysmenu_parent_id', dropdown_where('sysmenu_id','sysmenu_name',"sysmenu_level = 1",'base_sysmenu'), ''); ?><br />
<label><?php echo $this->lang->line('menu_link'); ?></label><?php echo form_input('sysmenu_link'); ?>*<br />
<label><?php echo $this->lang->line('menu_sequence'); ?></label><?php echo form_input('sysmenu_sequence','','size=12, maxlength=2'); ?>*<br />
<label>&nbsp;</label><?php //echo form_submit('data',$this->lang->line('btn_save')); ?>
<?php echo form_close(); ?>

Upvotes: 0

Views: 9328

Answers (3)

Md. Nazrul Islam
Md. Nazrul Islam

Reputation: 3017

Using The Following Criteria.

In Controller Class Use a method to initial the View Page.

 public function CreateStudents() {

        $this->load->helper('form'); // include form helper

        $data['title'] = "Create Students Page"; //Title of the page

        $this->load->view('templates/header', $data); // header
        $this->load->view('createstudents', $data);  // main content
        $this->load->view('templates/footer', $data); // footer
    }

Then create the Ajax Method. When submit the form this method is execute.

 public function CreateStudentsAjax() {

    $this->load->helper('form');
    $this->load->library('form_validation');
    $this->form_validation->set_error_delimiters('', '');

    $this->form_validation->set_rules('roll', 'Roll Number', 'required');
    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('phone', 'Phone', 'required');

    if ($this->form_validation->run()) {

        $this->welcome_model->InsertStudents();
        echo json_encode("Oks");
    } else {

        $data = array(
            'roll' => form_error('roll'),
            'name' => form_error('name'),
            'phone' => form_error('phone')
        );

        echo json_encode($data);
    }
}

In View page add a Form

 <div id="message">


 </div> 

<?php echo form_open('welcome/CreateStudentsAjax'); ?>

    <label for="roll">Student Roll Number</label>
    <input type="text" id="txtRoll" value="" name="roll"/>

    <label for="Name">Students Name</label>
    <input type="text" id="txtName" value="" name="name"/>

    <label for="Phone">Phone Number</label>
    <input type="text" id="txtPhone" value="" name="phone"/>

    <input type="submit" name="submit" value="Insert New Students"  />

    <?php echo '</form>'; ?>

The Scripts is

<script type="text/javascript">

        $(document).ready(function(){

            $('form').submit(function(){
                //alert('ok');      
                $.ajax({
                    url:this.action,
                    type:this.method,
                    data:$(this).serialize(),
                    success:function(data){
                        var obj = $.parseJSON(data);

                        if(obj['roll']!=null)
                        {                               
                            $('#message').text("");
                            $('#message').html(obj['roll']);
                            $('#message').append(obj['name']);
                            $('#message').append(obj['phone']);
                        }
                        else
                        {                               
                            $('#message').text("");
                            $('#message').html(obj); 
                        }

                    },
                    erro:function(){
                        alert("Please Try Again");
                    }                        
                });
                return false;
            });                        
        });

    </script>

This are all. Hope all enjoy the code.

Upvotes: 1

Zaher
Zaher

Reputation: 1150

i will try to help but you will have to test it :

  1. make sure that your form is return false, so that you will disable the default behavior of it ( as in http://s.zah.me/IouBgK but with some modification, add return false; and change the data to be data : $('#yourformID').serialize(), ).
  2. you will have to check your submitted data in your controller to see if its an ajax request or not using the $this->input->is_ajax_request() and then you will echo the result of the validation or whatever your controller will do .

Upvotes: 0

Bekodo
Bekodo

Reputation: 176

You have to submit your form manually, and handle success/error inside the AJAX call.

Call a function like this from within Save:

function submitForm(){

 $.ajax({
  type : "POST",
  url : "sysconfig/sysmenu/create",
  data : postData, // Add your form data as inputname1=value1&inputname2=value2....
  success : function(data) {
   // Show OK message
  },
  error: function(error){
   // Show error message
  }
 });
}

Upvotes: 0

Related Questions