I've got a form for a contact database where the user can click a plus symbol and add infinite number of phone entry fields, email fields, address fields. I've already found out how to do this from other questions answered.
Now I need to know how to process that data. Each field which can be added infinitely has the same name. I was thinking these would be added to an array in which I could use a for or .each and loop through it.
One last thing is that I was sending this information through jQuery Ajax to a PHP page which would process all the data. I'm much more skilled in PHP than I am in jQuery, but jQuery is useful for not having to refresh a page, obviously. My question is is this bad practice? It seems to be a little slower. I know I could error check and process the data in js then send the processed data to a PHP page to be input in a database but I'm worried on how much harder it is to error check with js.
When adding form elements, note that if you add square brackets to the end of the name, the posted data will be structured as an array-like object:
<input type="text" name="extrainput[]"/>
You can then iterate over the results and process user input.
So for example if you needed to have an indefinite number of textboxes for the user to enter his languages, you would use:
$('#addbutton').click(function(){
$('#myform').append('<input type="text" name="languages[]"/>')
});
where addbutton
is the id of the button the user would click to add another input.
To iterate over these form elements, you can use:
$('[name="languages[]"]').each(...)
Two ways to approach it, both have a similar result in PHP
Row 1
<input type="text" name="fullname[]" />
<input type="text" name="telephone[]" />
Row 2
<input type="text" name="fullname[]" />
<input type="text" name="telephone[]" />
Etc
$_POST will have an array of values whose indexes show which row they belong to
Row 1
<input type="text" name="row[1][fullname]" />
<input type="text" name="row[1][telephone]" />
Row 2
<input type="text" name="row[2][fullname]" />
<input type="text" name="row[2][telephone]" />
$_POST will have an array per row
you can simply use
jQuery(yourDiv).data('mydata', anyObject);
and then iterate
jQuery(selector of your divs).each(function(item){
var obj = jQuery(item).data('mydata');
// do anything you want here
})
you can use an array as name in html :
var i = 0;
$('.add').click(function(){
var newE = $('<input/>').attr({type:'text',name:'data[]',value:i,'class':'inputs'});
$('.myform').append(newE).hide().fadeIn('1000');
});
and for sending with ajax :
var data = {};
$.each($('.inputs'),function(i,val){
data[i] = $(val).val();
});
callajaxfunction(data);
and then you can get this array with php :
foreach($_POST['data'] as $key => $value){
echo $key.':'.$value.'<br>';
}