Waxi
Waxi

Reputation: 1651

How to format 2 variables for 1 ajax call so I can use the data easily?

I have this click event...

$('#save').on('click', function(){

    var employee = $('#employee').serialize(); // form with name, phone, email etc.

    var training = []; // empty array for now

    $('.entry').each(function(){

        var tid = $(this).attr('id'); // number
        var start = $(this).find('#start').val(); // date
        var expiration = $(this).find('#expiration').val(); // date

        var entry = [tid, start, expiration]; // create array with data

        training.push(entry); // push each entry into array

    });

    $.ajax({

        method: 'post',
        url: 'brain.php',
        data: {'training':training, 'employee':employee},
        success: function(results) {

            console.log(results)

        } 

    });

});

The PHP receiving this call looks like this...

 $employee = $_POST['employee']; // has string of input values
 $training = $_POST['training']; // has array of entries

Now this works, I receive both variables, but they're kinda hard to work with for my purposes, which is putting them into a database. I really don't know how to get the data out easily. I would like something like this...

$firstName = $_POST['employee']['first-name']; // first-name input
$lastName  = $_POST['employee']['last-name']; // last-name input

$entry1 = $_POST['training'][0]; // array data found in 0
$entry2 = $_POST['training'][1]; // array data found in 1

My question is, what do I have to change in the javascript or the PHP to get what I want and to make this stuff easier to work with? I think I'm missing a key concept here.

Upvotes: 0

Views: 52

Answers (1)

user1189882
user1189882

Reputation:

In my opinion, since you don't have much data, you can just manually create an object for the employee instead of using serialize. You can also use objects for your training entries, instead of arrays, then each spot in the training array has one object to represent the training with an ID corresponding to its location in the training array. That's a little wordy, but here's what I mean:

$('#save').on('click', function(){

    var employee = {
        "first-name":$('#employee').find('[name=first-name]').val(),
        "last-name":$('#employee').find('[name=last-name]').val()
    };

    var training = []; // empty array for now

    $('.entry').each(function(){

        var tid = $(this).attr('id'); // number
        var start = $(this).find('#start').val(); // date
        var expiration = $(this).find('#expiration').val(); // date

        var entry = {start:start,expiration:expiration}; // create object with data

        training[tid] = entry; // push each entry into array, using ID of entry as index

    }); 
    var data = {employee:employee, training:training};

    //POST function here - use data variable as data
});

And here's a fiddle: http://jsfiddle.net/x2hfb719/

Upvotes: 1

Related Questions