codeigniter ajax form submit

ajax, codeigniter, form-submit, jquery, preventdefault

Solution

Try your luck with the `submit` event instead of `click`:

$('form').submit(function(e){//
   e.preventDefault();
    var first_name = $('#register_form1').val();


    $.ajax({
        type: "POST", 
        async: false, 
        url: base_url+"register/registration_val",   
        data: "register_first_name="+first_name,
        success: function(data){
            $('#inferiz').html(data);
        },
        error: function(){alert('error');}
    });     
});

If the from has an `id` replace `'form'` with `'#{formId}'`.

Notes:

- The code should be inside a DOM ready event callback.

- If the form doesn't exist on DOM ready, you should use delegate event.

Like with this:

$('body').on('submit', 'form', function(e){
   e.preventDefault();
    var first_name = $('#register_form1').val();    

    $.ajax({
        type: "POST", 
        async: false, 
        url: base_url+"register/registration_val",   
        data: "register_first_name="+first_name,
        success: function(data){
            $('#inferiz').html(data);
        },
        error: function(){alert('error');}
    });     
});

Just replace `body` with a closer static element (if there is one) to enhance performance.

Good Luck!

Problem

i have a form (made through codeigniter) that i want to submit with ajax onClick. Form submits without Ajax and doesnt let me do `event.preventDefault();` jQuery file ``` $('#register_submit').click(function(e){// e.preventDefault(); var first_name = $('#register_form1').val(); $.ajax({ type: "POST", async: false, url: base_url+"register/registration_val", data: "register_first_name="+first_name, success: function(data){ $('#inferiz').html(data); }, error: function(){alert('error');} }); }); ``` // Controller works just fine. name register, function that i POST to is registration_val HTML file ``` <form method="POST" action='<?php echo site_url('/register/registration_val'); ?>' id='register_form' > <input type="login" name="register_first_name" id="register_form1"> <input type='submit' value="Register" id='register_submit'> </form> ``` Problem is, when I click on SUBMIT button, jQuery doesnt do its work, instead, form submits itself to the controller and gives out an ERROR message. I cannot prevent the form from submitting (which i think would solve the problem), the Click event is completely ignored. Thanks in advance

Original source