I'm using Codeigniter and I have a dynamically created form with lots of input fields. I'm using jQuery and AJAX to submit form and I'm passing all the data from form as an object. This is my jQuery code:
$('body').on("submit", "#app-options-form", function(evnt){
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
// Prevent form submission
evnt.preventDefault();
// Get all form inputs
var inputs = $('#app-options-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"edit_form_submited" : true, "data" : data},
function (data) {
$('.response-container').html(data.result);
}, "json");
});
I'm having difficulties with validation of that form. If I put a field name as a parameter for set_rules(), it won't work because it will look for $_POST['field_name'] but this doesn't exist. The value of this field is passed as $_POST['data']['field_name'], because I'm passing all inputs as an object called "data".
So, is there any way to validate this form?
EDIT:
My PHP code:
// Get received data, here are all the input fields as $field_name=>$field_value
$data = $this->input->post('data');
// Try no. 1 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 2 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($value, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 3 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($this->input->post('data')['$key'], 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
These are my tries to set the rules, but none of them works