CodeIgniter Forums

Full Version: Parse HTML table data and insert_batch effectively?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

I've created a register page, where a user can register as many addresses addresses as he wants, each time he clicks in the button 'Add', it calls a javascript method to insert the inputs data to the row.

So only when he clicks on 'Submit' button, it will insert all the adresses rows from the table to the database.

I'm having trouble to do that, I've been able to parse HTML table data with jQuery:
    $('#output').html('OUTPUT: '+tableToJson('#mytable'));

function tableToJson(table){
    var AoA = $(table+' tr').map(function(){
        return [
                return $(this).text();
    return JSON.stringify(AoA);

Output: [["Juan","23","1990"],["Jonhatan","25","1980"],["Pete","20","1991"]]
But the problem is that it doesn't return the value with keys.

I've also tried to parse the table, to be an array of dictionaries, with keys and values, but it didn't make easier to insert to the database, because it when the json was decoded, the format of the keys : values wasn't right for PHP.

JsFiddle example:

I guess the simplest,most efficient solution would be insert_batch but without specifying the fields, like:

It would be good to do that without having to manipulate data a lot, like having to create an array and then format this array with another method, it would be something too extensive.

Does anyone have a better idea to keep table rows registries on a variable and only send it when Ajax post is called?

Maybe an approach with only two steps, generating the array and then inserting the array.

Thank you very much.

El Forum

I wouldn't worry about sending the keys. That would double the bytes needed to transfer anyway. But try just sending the values array and do something like this:

$keys = array('name', 'age', 'random');

$values = '[["Juan","23","1990"],["Jonhatan","25","1980"],["Pete","20","1991"]]'; //This would be coming from your ajax
$values = json_decode($values);

foreach($values as $c => $subarr)
$values[$c] = array_combine($keys, $subarr);


    [0] => Array
            [name] => Juan
            [age] => 23
            [random] => 1990

    [1] => Array
            [name] => Jonhatan
            [age] => 25
            [random] => 1980

    [2] => Array
            [name] => Pete
            [age] => 20
            [random] => 1991

Probably not exactly what you wanted, but best I could think of in a few minutes. Smile

El Forum

Thank you for your help.
I think there isn't an alternative but manually format these arrays.

El Forum

Yeah, if javascript supported associative arrays it'd be a lot easier.