1

Initially I am trying to load two views from one controller.

On submission I am passing one view to one controller and another view to another controller using ajax dynamically. Here is the skeleton of the controller

function edit(){     
    if (!$this->login_model->is_logged_in())
    {
        redirect('auth/login', 'refresh');
    }   
    $this->load->library('form_validation');    
    $this->data['custom_error'] = '';

        //------------- Getting Student data----------------

    if ($this->form_validation->run('students') == false)
    {
         $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);

    } else
    {                            
        $data = array(
                'username' => $this->input->post('username'),
                'city' => $this->input->post('city')
        );

        if ($this->student_model->edit('students',$data,'id',$this->input->post('id')) == TRUE)
        {
            redirect(base_url().'index.php/students/manage/');
        }
        else
        {
            $this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';

        }
    }

    $this->data['result'] = $this->codegen_model->get('students','id,username,city,created_on,date_created','id = '.$this->uri->segment(3),NULL,NULL,true);

    $this->data['message'] = $this->db->get('messages')->result();

            //---------------------- Posting student data for Edit--------------
    $this->load->view('pheader');
    $this->load->view('/students/students_edit', $this->data);  

            //-------- loading comment controller for comment box --------------
            $msg_data['result'] = $this->db->get('messages')->result();
            $this->load->view('commentView', $msg_data);
}

So the problem is when I m submitting the messages_view both the controllers are loaded , but I need to load only one controller

Here is my student_edit view where I edit my details

<?php     

echo form_open(current_url()); ?>
<?php echo $custom_error; ?>
<?php echo form_hidden('id',$result->id) ?>

        <p><label for="username">Username<span class="required">*</span></label>                                
        <input id="username" type="text" name="username" value="<?php echo $result->username ?>"  />
        <?php echo form_error('username','<div>','</div>'); ?>
        </p>

        <p><label for="city">City<span class="required">*</span></label>                                
        <input id="city" type="text" name="city" value="<?php echo $result->city ?>"  />
        <?php echo form_error('city','<div>','</div>'); ?>
        </p>
        <?php echo form_submit( 'submit', 'Submit'); ?>
</p>

<?php echo form_close(); ?>

Here is the commentView that I am loading separately from the controller

<div id="content-table-inner">
    <table border="0" width="100%" cellpadding="0" cellspacing="0">
        <?php foreach ($result as $comment): ?>

            <tr valign="top">
                <p>Posted By : <?=$comment->created_by?></p> 
                <p>Posted On : <?=$comment->created->on?></p> 
                <p>Message : <?=$comment->message?></p> 
            </tr>
            <br/>
        <?php endforeach; ?>
        </table>
        <div class="submitComment" id="insertbeforMe">
            <h3>Add a message</h3>
            <form id="form" method="POST" action="">
             <p>
                 <textarea name="message"></textarea>
            </p>
                <input type="hidden" value="<?=base_url()?>" id="baseurl"/>
                <button name="submit comment">Submit Comment</button>
            </form>
        </div>
        <script type="text/javascript">
        function comment(){
            var baseurl = $('#baseurl').val();
            $('.submitComment').click(function(){
                $.ajax({
                    url : baseurl + 'index.php/comment/insert',
                    data : $('form').serialize(),
                    type: "POST",
                    success : function(comment){
                        $(comment).hide().insertBefore('#insertbeforMe').slideDown('slow');
                    }
                })
                return false;
            })
        }
        </script>

</div>

Can anyone tell me whats the problem ?

3
  • why not you change ajax to call the controller instead? Commented Feb 19, 2013 at 7:23
  • @ajreal : I ll have two form submissions then how can I submit two different forms to two different controllers in one web page ? Commented Feb 19, 2013 at 11:09
  • the two requests can be merge into one Commented Feb 19, 2013 at 12:22

2 Answers 2

2

If I understand correctly...

The event you should be capturing is the form's "submit", not the submit-button's "click". You're essentially running the AJAX request and submitting the form.

Try something like this instead:

$('form').on('submit', function(e) {
    e.preventDefault(); // this prevents the form from submitting

    // do AJAX stuff
});
Sign up to request clarification or add additional context in comments.

Comments

0

Unless I am mistaken you are attaching the event to a click event on the '.submitComment' div.

Should you not give the button an id and attach the .click event to it ? Then you need to define the view you want to call via ajax to return some json which your function can use:

The Javascript:

       $('#button').click(function(){
                    $.ajax({
                        url : baseurl + 'index.php/comment/insert',
                        data : $('form').serialize(),
                        type: "POST",
                        dataType: "json",
                        success : function(comment){
                            $('table').append('<tr><p>'+comment.createdby+'</p><p>'+comment.createdon+'</p><p>'+comment.message+'</p></tr>');
                        }
                    })
                    return false;
       })

The Controller method (comment/insert):

function insert() {
    $comment = $this->input->post('message');
    $result = $this->commentModel->insert($comment);
    if($result["OK"]) {
        $data['json'] = json_encode(array('createdon' => $result["createdon"], 'createdby' => $result["createdby"], 'message' => $result["message"]));
        $this->load->view('json_comment_view', $data);
    }
    //ELSE deal with errors (flashdata etc...)
} 

The View (loaded via ajax):

<?php
    $this->output->set_header('Content-Type: application/json; charset=utf-8');
    echo $json;
?>

I haven't tested this code - or used codeigniter extensively in about a year, but the concepts covered should put you on the right track for what you want to achieve. Let me know!

5 Comments

Still not getting it as the previous form is still throwing flash errors
Could you clarify ? What previous form ? Also - what errors are you receiving exactly ? Thanks.
Like I have two views edit_person_details_view and comments_view both coming from different controller but displayed on same web page. I need the submission of both to happen separately. How can I do that ?
You need one controller to load a view as normal. Then from within that view you should use javascript to call another controller which in turn loads its own view. This second view is loaded into the same page as the first using jQuery load or ajax calls. Can you provide additional source code for the other views? Only one form is showed in your question.
In your additional code, beneath your comment : // loading comment controller for comment box You don't actually load another controller, you load an additional view. In your original question you also say that a problem occurs when you submit the messages_view is that the commentView? You also say that you have two forms, and need their submissions to be separate from the other. I presume that you mean when you submit the second form the first form displays validation errors? If there is more than one form on the page you should use a class or id selector for the form in your ajax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.