How to send weekly timesheet data from JavaScript frontend?

2 weeks ago 23
ARTICLE AD BOX

Short answer:

Your AJAX request is fine, but PHP does not automatically parse JSON into $_POST. You must read raw input using php://input.

For the database, you should store each day as a separate row (normalized structure). Do not store all days as columns in a single row.


Receiving JSON in PHP

Since you are sending: Content-Type: application/json

You must handle it like this:

"Invalid JSON"]); exit; } $week = $data['week']; $hourlyRate = $data['hourlyRate']; $totalPay = $data['totalPay']; echo json_encode([ "status" => "success", "received" => $data ]); ?>


Debugging tip

To verify what is actually being received:

file_put_contents("debug.txt", $raw);

This helps confirm whether the issue is in JavaScript or PHP parsing.


Recommended database structure

Do not use this type of structure:

mon_start | tue_start | wed_start | ...

This is hard to maintain and query.

Instead, use a normalized schema.

Table: timesheets

id (primary key) user_id week_start_date hourly_rate total_pay created_at

Table: timesheet_entries

id (primary key) timesheet_id (foreign key) day (mon, tue, wed, etc.) start_time (TIME or DATETIME) end_time (TIME or DATETIME) break_minutes (integer) total_hours (decimal)


Example insert logic in PHP

foreach ($week as $day => $entry) { $start = $entry['start']['hour'] . ":" . $entry['start']['minute'] . " " . $entry['start']['ampm']; $end = $entry['end']['hour'] . ":" . $entry['end']['minute'] . " " . $entry['end']['ampm'];

$breakMinutes = ($entry['breakHours'] * 60) + $entry['breakMinutes']; // Insert into database here using prepared statements
Optional improvement (modern JS)

Instead of XMLHttpRequest, you can use fetch:

fetch("/save-timesheet.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }) .then(res => res.json()) .then(res => console.log(res)) .catch(err => console.error(err));


Final recommendation:

Use php://input to read JSON in PHP. Use a normalized database with one row per day. Avoid storing all days in a single row with multiple columns.

Read Entire Article