Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter show errors individually next to form field with ajax callback

I'd made a form using CI and have a native form_validation() library to validate each fields input, I using jQuery post to callback the input to check whether each fields is valid, how if I want each error to populate into form_error() next to each field instead of validation_errors()?

Please refer to below:

view:

<script>
$("#btnregister").click(function() {
    var parameters = $("#reg_form").serialize();

    $.post(baseurl+'pages/registration', parameters, function(data) {
        if(data == "ok") {
            //show success message
        }else{

            $("#error").html(data); 

        }
    }, "html");
});
</script>


<div id="error"></div>
<form id="reg_form" method="post">
     <p>
     <label for="reg_username">Username</label><br />
     <input type="text" id="reg_username" name="reg_username" value="<?php echo set_value('reg_username'); ?>">
     <?php echo form_error('reg_username'); ?>
     </p>

     <p>
     <label for="reg_email">Email</label><br />
     <input type="text" id="reg_email" name="reg_email" value="<?php echo set_value('reg_email'); ?>">
     <?php echo form_error('reg_email'); ?>
     </p>

     <p><input type="button" id="btnregister" value="Register"></p>
</form>
</div>

Controller:

public function registration(){
    $this->load->library('form_validation');

    $this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
    $this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');


    if($this->form_validation->run() == FALSE){
        echo validation_errors();

    }else{
        // insert to db
        echo "ok";
    }
}

Thanks for help.

like image 276
conmen Avatar asked Dec 21 '12 00:12

conmen


1 Answers

You'll have to build your own error array. It would be nice if we could access the Form_validation's $_error_array but unfortunately it's protected and there's no access method for it.

I'm going to change your controller to output a json response to make this easier:

public function registration()
{
    $this->load->library('form_validation');
    $this->form_validation->set_rules('reg_username', 'Username', 'trim|required|min_length[4]|max_length[15]|xss_clean|is_unique[users.username]');
    $this->form_validation->set_rules('reg_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
    if ($this->form_validation->run())
    {
       $response['status'] = TRUE;
    }
    else
    {
        $errors = array();
        // Loop through $_POST and get the keys
        foreach ($this->input->post() as $key => $value)
        {
            // Add the error message for this field
            $errors[$key] = form_error($key);
        }
        $response['errors'] = array_filter($errors); // Some might be empty
        $response['status'] = FALSE;
    }
    // You can use the Output class here too
    header('Content-type: application/json');
    exit(json_encode($response));
}

Now your ajax success callback can read the status and errors keys of the response. You can loop through data.errors and add each one to the input field:

$("#reg_form").submit(function() {
    var form = $(this);
    $.post(baseurl+'pages/registration', form.serialize(), function(data) {
        if (data.status == true) {
            //show success message
        }else{
            $.each(data.errors, function(key, val) {
                $('[name="'+ key +'"]', form).after(val);
            });​
        }
    }, "json");
});

Another easy way is to post the form to itself, and have your ajax response reload the entire form - that way the messages and validation filters will be taken care of server-side.

like image 61
Wesley Murch Avatar answered Oct 24 '22 03:10

Wesley Murch