Reputation:
I was trying to include two variables along with a serialized form in a $.post call, and the only way I've found to do that is instead use serializeArray() rather than serialize(), and then add the extra variables into the array. All of the form elements are being processed correctly, but the extra two variables (order and column) are not.
JQ:
var order = 'asc';
var column = 'description';
$('#task_form').submit(function(e){
var formData = $("#task_form").serializeArray();
formData.push({column: column, order: order});
$.post('process.php', formData, function(data){
// clear the current task table
$('#tbody').empty();
// refresh the task table with the newly inserted task
$(data).appendTo('#tbody');
$('#tasks_table').trigger('update');
$("#description_text").val('');
});
e.preventDefault();
});
PHP:
if(isset($_POST['description_text'])){
$description = $_POST['description_text'];
$duration = $_POST['duration_text'];
$deadline = $_POST['deadline_text'];
$order = $_POST['order'];
$column = $_POST['column'];
TaskDB::createLog($order.' '.$column);
// convert the date
$pieces = explode('/', $deadline);
$month = $pieces[0];
$day = $pieces[1];
$year = $pieces[2];
$newDate = $year.'-'.$month.'-'.$day;
// create a new task object, add it to database
$task = new Task('DEFAULT', $description, $duration, $newDate, '0');
TaskDB::addTask($task);
TaskDB::generateTaskTable();
}
Anyone know why this is?
Upvotes: 0
Views: 93
Reputation: 227310
serializeArray
returns an array of objects, each containing {name: 'fieldName', value: 'fieldValue'}
.
You would need to push your values on in the same format.
formData = formData.concat([{name: 'column', value: column}, {name: 'order', value: order}]);
OR
formData.push({name: 'column', value: column});
formData.push({name: 'order', value: order});
Another solution is to use serialize()
and $.param
.
var formData = $("#task_form").serialize();
formData += '&'+$.param({column: column, order: order});
Upvotes: 0
Reputation: 1202
The serializeArray method generates an array of objects, which contain the keys and values. Try this code:
formData.push([{name: 'column', value: column});
formData.push([{name: 'order', value: order});
Upvotes: 0
Reputation: 3732
According to the serialize array documentation (http://api.jquery.com/serializeArray/) you need to reformat your appending to the array.
It takes name
,value
pairs.
You'd want to format your appends like so:
formData.push({name: "column", value: column});
And I'm sure you can figure out the rest.
Upvotes: 3