Zeehan Akhtar Mohammed Zeehan Akhtar Mohammed - 3 years ago 82
PHP Question

Validation in AJAX Form Codeigniter

I've made a form in Ci which submits the data to the Db. I've been trying to implement validation in the form, For eg Name : more than 3+ Letters, email '@' Etc.

I never could seem to make it work, tried using Jquery validation with different sources , the form basically submits without Validation, Any pointers to where i'm going wrong?

The code below is just a snippet without any validation codes attached to it.

<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title">Enquire About "<?php echo $row_company->company_name; ?> "</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#click_form').click(function () {
var url = "<?php echo site_url('enquiry/ajax_post_form') ?>";
var data = $("#reg_form").serialize();
$.post(url, data, function (data) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}, "json");

});
});

</script>
</div>
</div>
</div>
</div>


Controller

public function ajax_post_form() {

$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags');

$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);

$this->insert_model->form_insert($user_data);
$data['message'] = 'Data Inserted Successfully';
echo json_encode($user_data);
}


Model

function form_insert($user_data){
$this->db->insert('pp_enquiry', $user_data);
}


**Validation **

function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var email = document.getElementById("email1").value;
var mobile = document.getElementById("mobile").value;
//Check input Fields Should not be blanks.
if (name == '' || email == '' || mobile == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var email1 = document.getElementById("email");
var mobile = document.getElementById("mobile");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Must be 3+ letters' || email1.innerHTML == 'Invalid email' || mobile.innerHTML == 'Invalid website') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}

Answer Source

You can find below mentioned solution.

PHP Validation

$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags|valid_email|min_length[3]');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags|min_length[10]|max_length[12]');

if ($this->form_validation->run() == FALSE) {
    $data['status'] = false;
    $data['error'] = validation_errors();
} else {
    $user_data = array(
        'name' => $this->input->post('username'),
        'email' => $this->input->post('email'),
        'mobile' => $this->input->post('mobile'),
        'college' => $this->input->post('college')
    );
    $this->insert_model->form_insert($user_data);
    $data['status'] = true;
    $data['message'] = 'Data Inserted Successfully';
}
echo json_encode($data);

jQuery Validation

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>

$(document).ready(function() {
    var $validator = $("#reg_form").validate({
        rules: {
            name: {required: true, minlength: 3, maxlength: 25},
            email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\@[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
            mobile: {required: true, minlength: 10, maxlength: 12, number: true}
        },
        messages: {
            email: {required: "Please enter valid Email Address"},
            mobile: {required: "Please provide valid Phone or Mobile number!"}
        }
    });
    jQuery.validator.addMethod("regex", function(value, element, regexp) {
        if (regexp.constructor != RegExp)
            regexp = new RegExp(regexp);
        else if (regexp.global)
            regexp.lastIndex = 0;
        return this.optional(element) || regexp.test(value);
    }, "Please provide valid email address.");

    $('#click_form').click(function(e) {
        e.preventDefault();

        var $valid = $("#reg_form").valid();
        if (!$valid) {
            $validator.focusInvalid();
            return false;
        } else {
            var url = '<?php echo site_url('enquiry/ajax_post_form') ?>';
            var data = $("#reg_form").serialize();
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType: 'json',
                beforeSend: function() {
                    // Code if required before Send
                },
                success: function(returnData) {
                    if (returnData.status) {
                        $('.ajax_success').html('Enquiry Submitted Successfully!');
                    }
                }
            });
        }
    });
});

Let me know if it not works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download