Welcome Guest, Not a member yet? Register   Sign In
jQuery Form go through e.preventDefault() to CodeIgniter controller if successful post


I have a form:

<?php echo form_open_multipart( 'new_account/validate_new_account', array('id' => 'main-form') ); ?>    
        <input type="text" id="text_id" name="text-name" />
        <input type="file" id="file_id" name="file_name" />
        // ...
        <input type="submit" id="main-submit" />
    <?php echo form_close(); ?>

I submit it to my controller's validate_new_account() function:

function validate_new_account()
        // validations here

        if ( $this->form_validation->run() == FALSE ) {
     // JSON-encoded validations
            $errors = json_encode( $this->form_validation->error_array() );
            echo $errors;
     } else {
            // next step
     $this->view_preview_form( $this->get_post_data() );

I use the jQuery Form Plugin to interact with the controller.

var options = {
        url: "<?php echo site_url('new_account/validate_new_account'); ?>",
        type: 'POST',
        dataType: 'json',
        success: function(data) {

          if (data.length === 0) {
            alert('Form successfully submitted!');
          } else {
            // echo validation errors from CodeIgniter
            alert("Some fields weren't answered successfully. Please answer them.");
            $.each(data, function(key, value){
              var container = '<div class="error">'+value+'</div>';
              $('.form-element input[name="'+key+'"]').after(container);

    $('#main-submit').click(function(e) {


Without my ajax function, the code above works perfectly but I have dynamically added elements which requires ajax to handle all validations or else these elements will be gone (bad UX).

So if I enable and use my ajax function, the validation errors from CodeIgniter are printed out how I want BUT if all validations are now correct, the form does not go to $this->view_preview_form( $this->get_post_data() );.

Why is this happening? I've search for similar problems but sadly none helped my weird case.

How can I get pass through e.preventDefault() if the form was sent successfully?


Use this

if (data.length === 0) {
            alert('Form successfully submitted!');
return false

Thank you sir!

Hello, someone already in SO got the solution. Thanks.


Theme © iAndrew 2016 - Forum software by © MyBB