0

I have researched this code that will make my validation with ajax.

My controller is:

public function create(){


    $data = array('success' => false, 'messages' => array());

    $this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
    $this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');

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

        $data['success'] = true;
    }else{
        foreach ($_POST as $key => $value) {
            # code...
            $data['messages']['key'] = form_error($key);
        }
    }

    echo json_encode($data);
}

And my javascript is:

<script>
    $('#form-user').submit(function(e){
        e.preventDefault();

        var me = $(this);

        // perform ajax
        $.ajax({
            url: me.attr('action'),
            type: 'post',
            data: me.serialize(),
            dataType: 'json',
            success: function(response){
                if (response.success == true){
                    alert('success');
                }else{
                    $.each(response.messages, function(key, value) {
                        var element = $('#' + key);

                        element.closest('div.form-group')
                        .removeClass('has-error')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger')
                        .remove();

                        element.after(value)

                    });
                }
            }

        });


    });


</script>

At first my if else statement was:

            if (response.success == true){
                alert('success');
            }else{
               alert('failed');

                });

But when i put the codes:

  $.each(response.messages, function(key, value) {
                        var element = $('#' + key);

                    element.closest('div.form-group')
                    .removeClass('has-error')
                    .addClass(value.length > 0 ? 'has-error' : 'has-success')
                    .find('.text-danger')
                    .remove();

                    element.after(value)

The button doesn't work anymore if the validation fails.

1
  • "The button doesn't work" isn't a proper technical problem description. Inspect the actual response from server for clues Commented Jun 11, 2016 at 12:26

1 Answer 1

1

You are hard coding the string 'key' in the php loop where you actually want the variable $key

Change

$data['messages']['key']

To

$data['messages'][$key]
Sign up to request clarification or add additional context in comments.

Comments

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.