Ryan Fung Ryan Fung - 1 year ago 86
PHP Question

On Form Submission, do jquery checking first before Codeiginiter validation

Form submission button, I have to check some validation using jquery. However I have also used codeiginiter validation with form_open(xxxx), which makes my submit button jQuery has not been called. How can I do to make both works? before or after? (I want front and backend checking)

<?php $prevURLPATH=urlencode($p); echo form_open('form/'.$usr.'/'.$name.'?prevURL='.$p); ?>

<div class="form-group row">
<label class="col-md-3 control-label text-center"></label>
<div class="col-md-8">
<button id="submit-upload-form" class="btn btn-primary btn-tw" onclick="setup(); return false;"><i class="glyphicon glyphicon-upload"></i>Submit</button>
<button id="validate" hidden="true" type="submit"></button>

function setup()
{ .......Checking some fields in the form...............}

What I want is:
On Form Submission, Jquery/JS checking (Frontend), then backend codeigniter form checking.

(It seems like when user click the submit button, it ignores all the jquery validation and go straight to codeigniter validation. I think if I use form_open() in php I am very limited right?)

I am following this link.

Hoping to find an answer so that other people will know the right way of working with codeiginiter validation.

Thanks for all your answers so far, however I still couldn't find the right solution yet. :( Anyone else please help?

Answer Source

If you want to validate in the client before submitting your form, the following will work:

// view
echo form_open('basic_controller/submission');
echo form_input( array('name'=>'text', 'id'=>'text_input') );
echo form_submit('my_submit', 'Enter', "id='my_submit'");
echo form_close();

// controller
function submission() {
    $field = $this->input->post('text');
    // add your checkings (backend)

So far, this is what you already had but simpler. Note that fields on the form have an ID. We can now manipulate and access the content of the form easily via jQuery. Add a click handler on the submit button:

    // view
    <script type='text/javascript'>    
        $(document).on('click', '#my_submit', function() {        
            var input_value = $('#text_input').val();

            // do your frontend checkings here
            alert('before form submission. ' + input_value);

Actually, there is no need to give the fields an ID, you only have to assign an ID to the submit button and then access the fields in some other way (I just did that for the sake of simplicity).


In your case, the script should be:

$(document).on('click', '#submit-upload-form', function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download