Hello,

I am developing a site with CI 2.1.3

I have a blog module, in this blog I have a form to post a comment.

I am calling this form inside a view with:
echo Modules:: run('blog/comment');

When I submit this form with ajaxForm, or refresh the page, the values of the input fields are not being cleared.

My controller’s function for the comment form:

public function comment($postId)
{
 $this->load->helper('form');
 $this->data['success'] = FALSE;
 $this->data['postId'] = $postId;

 if(!isset($_POST['comment_submit']))
 {     
   $this->data['new_comment'] = $this->blog_comment_m->get_new();
 }
 else
 {
  $this->data['new_comment'] = $this->blog_comment_m->object_from_post(array('author', 'authur_email', 'content'));
  $this->load->library('form_validation');
  $rules = $this->blog_comment_m->rules;
  $this->form_validation->set_rules($rules);

  if($this->form_validation->run() == TRUE)
  {
    $this->data['success'] = TRUE;
        $this->data['new_comment'] = $this->blog_comment_m->get_new();
  }
 }

 $this->load->view('add_comment', $this->data);
}

The comment form:

<div id="commentAjax">
<?php $attr = array('id'=>'commentForm'); echo form_open(site_url('blog/comment/' . 

$postId), $attr); ?>
  <input type="hidden" name="post_id" value="<?php echo $postId; ?>" />
  <div style="border-top:2px groove #930"><h4>Leave a Comment</h4></div>

  <div class="control-group <?php if(form_error('author')) echo 'error'; ?>">
    <label>Name *</label>
    <?php echo form_input(array('name'=>'author', 'class'=>'input-large', 'value'=>set_value('author', $new_comment->author))); ?>
    <span class="help-block"><?php echo form_error('author'); ?></span>
  </div>

  <div class="control-group <?php if(form_error('author_email')) echo 'error'; ?>">
    <label>Email *</label>
    <?php echo form_input(array('name'=>'author_email', 'class'=>'input-large', 'value'=>set_value('author_email', $new_comment->author_email))); ?>
    <span class="help-block"><?php echo form_error('author_email'); ?></span>
  </div>

  <div class="control-group <?php if(form_error('content')) echo 'error'; ?>">
    <label>Comment *</label>
    <?php echo form_textarea(array('name'=>'content', 'value'=>set_value('content', $new_comment->content))); ?>
    <span class="help-block"><?php echo form_error('content'); ?></span>
  </div>
   <div>
        <?php echo form_submit('submit', 'Send Comment', 'class="btn btn-submit"');?>
      <input type="hidden" name="comment_submit" value="1" />
  </div>
  <?php echo form_close(); ?>

    <?php if($success): ?>
    <div style="border:1px solid #666; background:#9F9; color:#000; margin-top:10px; width:50%; padding:5px; font-weight:bold">
      <p>Thank you for your comment.</p>
      <p>To avoid spam, your comment has been submitted for approval.</p>
      <p><h2 class="highland">Highland Coffee Roastery</h2></p>
    </div>
  <?php endif; ?>
</div>
<script>
$(function()
{                        
    var options = { target: '#commentAjax' };
    $('#commentForm').ajaxForm(options);
});
</script>

I dumped the $new_comment array and the fields values are empty.

I checked the page source and the input fields values = ''.

Yet, I still see the values that I submitted in the input fields.

Why is that?

Recommended Answers

All 13 Replies

What it does $this->data['new_comment'] = $this->blog_comment_m->get_new(); ? I see it's used in two cases:

  1. GET request, no form submit;
  2. and when validation is true, rewriting a previous setting of $this->data['new_comment'].

In the first case the objects should return null/false, so that the default value for set_value('name', $default) is empty.

Hi cereal,

What it does is creating an object with the input fields and setting their values to blanks.

Ok, the problem is that set_value() doesn't consider if the validation runs true or false, usually you redirect() and so the POST array is resetted automatically, here we can force this action by extending /system/libraries/Form_validation.php, create /application/libraries/MY_Form_validation.php and paste this:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_Form_validation extends CI_Form_validation {

    public function __construct()
    {
        parent::__construct();
    }

    public function resetpostdata()
    {
        $obj =& _get_validation_object();
        foreach($obj->_field_data as $key)
        {
            $this->_field_data[$key['field']]['postdata'] = NULL;
        }
        return true;
    }

}
?>

After the validation runs true, call the method, as in this example:

if($this->form_validation->run() === FALSE)
{
    # . . .
}
else
{
    $this->form_validation->resetpostdata();

    # load view & other stuff
}

It should work fine, bye.

cereal you're a STAR !!!!

I've been struggling with this problem for days, posted about it all over the world, your solution sloved the problem.

I can't thank you enough !!!

THANK YOU ! :)

You're welcome, if we are done, please mark it solved, it will be useful to others :)

Ok, I still have a problem, when I refresh the page, after submitting the form, the values are back in the input fields.... any idea how to fix that as well?

Can you explain better the problem? I've created a test with ajaxForm and it's working fine, here's the code:

The Controller
<?php

class Test extends CI_Controller {

    protected $data;

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'name', 'trim|required|prep_for_form|xss_clean');
        $this->form_validation->set_rules('comment', 'comment', 'trim|required|prep_for_form|xss_clean');
        $this->data['last_comment'] = FALSE;

        if($this->input->server('REQUEST_METHOD') == 'POST')
        {
            if($this->form_validation->run() === FALSE)
            {
                $this->data['error'] = 'Ops!';
            }
            else
            {
                $this->data['error'] = 'POST Requests';
                $this->data['last_comment'] = array(
                    'name'      => $this->input->post('name'),
                    'comment'   => $this->input->post('comment')
                    );

                # empty the values retrieved by set_value()
                $this->form_validation->resetpostdata();
            }
        }
        else
        {
            $this->data['error'] = 'GET Request';
        }
        $this->load->view('test/test', $this->data);
    }

}
The View
<!DOCTYPE html>
<html lang="en">
<head> 

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script type="text/javascript" src="/js/bootstrap.min.js"></script>

    <link href="/css/bootstrap.min.css" rel='stylesheet' type='text/css' />

    <style type="text/css">
        body { padding:50px; }
    </style>

    <script>
        $(document).ready(function() { 
            var options = { target: '#commentAjax' };
            $('#commentForm').ajaxForm(options); 
        }); 
    </script> 
</head>
<body>
<?php

$data = array(
            array(
                'name'  => 'name',
                'id'    => 'name',
                'class' => 'input-xlarge',
                'value' => set_value('name', 'your name'),
            ),
            array(
                'name'  => 'comment',
                'id'    => 'comment',
                'class' => 'input-xlarge',
                'value' => set_value('comment', 'your comment'),
            ),
            array(
                'value' => 'Submit',
                'type'  => 'submit'
            )
        );

echo '<div id="commentAjax">';
echo "<h3>$error</h3>";
echo form_open('/test/index', array('id' => 'commentForm'));
echo '<label for="name">Name</label>'.form_input($data[0]);
echo '<label for="comment">Comment</label>'.form_textarea($data[1]).'<br />';
echo form_submit($data[2]);
echo form_close();
if($last_comment !== false)
{
    echo '<h4>'.$last_comment['name'].'<h4>';
    echo '<p>'.$last_comment['comment'].'</p>';
}
?>
</div>
</body>
</html>
Update of MY_Form_validation.php
public function resetpostdata($reset = false)
{

    if($reset === true)
    {
        $_POST = array();
    }

    $obj =& _get_validation_object();

    foreach($obj->_field_data as $key)
    {
        $this->_field_data[$key['field']]['postdata'] = NULL;
    }

    return true;
}

In practice by setting TRUE to resetpostdata() method you can reset $this->input->post():

$this->form_validation->resetpostdata(TRUE);

By running the example you can see that the form resets after you submit the request, and also when reloading the page. It's not perfect because it replicates the entire page instead of the single form and of the new comment, but this is just a test...

Hi cereal,

Sorry, I wasn't on my comupter the whole day.

My problem is that I submit the form successfuly. The input fields are cleared. Then I refresh the page, and the input fields have the values that I submitted in them again.

I will look at your code deeper tomorrow as I can't do it now.

Looked at it quickly and it is a bit different than my code, so I need to figure out why your code works and mine doesn't.

I will post here if I find the solution.

Thank you very much for all the effort.

Just one more thing, the strangest thing is, after I refresh the page, I look at the page source and the fields values are equal ''. For example:

<div class="control-group ">
    <label>Name *</label>
    <input type="text" name="author" value="" class="input-large"  />    <span class="help-block"></span>
  </div>

But on th page itself I see this: Name: cgull, which is the name I inserted into the field and then submitted the form.

The source says value = '' so how does it display cgull in the name field???

This is driving me nuts.

Do you get the same effect with different browsers? I can think to an autofill issue here, if you're using HTML5 you can avoid it by adding autocomplete="off" to the input fields.

cereal, you found it! autocomplete, solved the problem.
I tested it on Chrome and it was fine without the autocomplete, but firefox needed it.
I just don't understand why does it happen only on this form and not on other forms in my app.
WOW, thank you very much.

You're welcome! :)

The problem is given by Firefox Form Manager, if in the form there are the words Name and/or Address (and variants) it will try to autocomplete it.

And I used to love Firefox.... lol

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.