Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8527115
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T08:27:52+00:00 2026-06-11T08:27:52+00:00

I’m new to stackoverflow and to CodeIgniter and I’m currently experimenting on some simple

  • 0

I’m new to stackoverflow and to CodeIgniter and I’m currently experimenting on some simple code examples I have found on the Internet in order to get a start. The one I’m working on right now is a form which uses CI and Ajax (jQuery) along with saving the inputs of the form in a database and then display the most recent of them on the same page as the form.
If I confused you it’s the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files just below.

Controller:

<?php
class Message extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->helper('security');
        $this->load->model('Message_model');
    }

    function view()
    {
        //get data from database
        $data['messages'] = $this->Message_model->get();

        if ( $this->input->is_ajax_request() ) // load inline view for call from ajax
            $this->load->view('messages_list', $data);
        else // load the default view
            $this->load->view('default', $data);
    }

    //when we pres the submit button from the form
    function add()
    {
        if ($_POST && $_POST['message'] != NULL)
        {
            $message['message'] = $this->security->xss_clean($_POST['message']);
            $this->Message_model->add($message);
        }
        else
        {
            redirect('message/view');
        }
    }
}
?>

Model:

<?php
class Message_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    function add($data)
    {
        $this->db->insert('messages', $data);
    }

    function get($limit=5, $offset=0)
    {
        $this->db->order_by('id', 'DESC');
        $this->db->limit($limit, $offset);

        return $this->db->get('messages')->result();
    }
}
?>

Views

default.php:

<!-- called using message/view -->
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script src="<?php echo base_url('js/jquery-1.8.1.min.js'); ?>" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                $('#submit').click(function(e)
                {
                    e.preventDefault();
                    var msg = $('#message').val();
                    $.post("", {message: msg}, function() {
                        $('#content').load("");
                        $('#message').val('');
                    });
                });
            });
        </script>
    </head>

    <body>
        <?php echo form_open("message/add"); ?>
        <input type="text" name="message" id="message">
        <input type="submit" value="submit" name="submit" id="submit">
        <?php echo form_close(); ?>

        <div id="content"></div>
    </body>
</html>

messages_list.php:

<!-- called from ajax call -->

<ol>
<?php foreach ($messages as $cur): ?>
    <li><?php echo $cur->message; ?></li>
<?php endforeach; ?>
</ol>

The problem mainly lies in the 1st of the views (default.php). That is, if I omit the e.preventDefault(); line from the javascript code then the form loads a different page (message/add as the form action parameter implies) which is a blank page, also cancelling the ajax behavior of my application that way.
On the other hand, if I actually add this line then the add method of my message controller isn’ t called, thus not adding what I’ve typed into the database.

Finally, I tried the following js code instead of the other above:

$(document).ready(function()
            {
                $('#submit').click(function(e)
                {
                    e.preventDefault();
                    var msg = $('#message').val();
                    $.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
                        $('#content').load("");
                        $('#message').val('');
                    });
                });
            });

but that way it seems as the $.post() crashes because nothing is executed in the function which is supposed to run on a successful post() call.

Any help appreciated and sorry for the big post. 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T08:27:54+00:00Added an answer on June 11, 2026 at 8:27 am

    You are correct that you must call e.PreventDefault();, but you must also deal with the response from the callback function, which you are not. The callback takes a few arguments but the first one is what you’re interested in, it is the response from your server. I’ve denoted it as r below:

    $(document).ready(function(){
        $('#submit').click(function(e){
            e.preventDefault();
            var msg = $('#message').val();
            $.post("<?php echo base_url(); ?>message/add", {message: msg}, function(r) {
                //do something with r... log it for example.
                console.log(r);
            });
        });
    });
    

    I’ve also removed $.("#content").load(...);. This would actually perform another AJAX request when the first one is complete.

    Now, inspecting your controller…please refrain from using $_POST. CodeIgniter provides you with $this->input->post() as part of the Input Library. If you turn on Global XSS filtering in config/config.php you won’t have to xss clean it either. You can clean on a post-by-post basis by using $this->input->post('name', true);

    I recommend this instead:

    function add(){
        $m = $this->input->post('message', true);
        if($m){
            $this->Message_model->add($m);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.