I’m working on a web application where I need to send a date from JavaScript to PHP using AJAX, then store it in a MySQL database. The problem is that I keep getting date format errors when trying to insert the data.
I’ve tried different approaches like sending the date object directly, converting it to JSON format, and using UTC conversion. But MySQL keeps rejecting the date format.
The specific error message I receive is:
Invalid date format: ‘Mon, 15 Mar 1985 08:30:00 GMT’ for column ‘user_birthdate’
Everything else in my code works perfectly. I can update all other database fields without issues. It’s only the date field that’s causing problems.
Here’s how I create the date in JavaScript:
var birthDate = new Date(selectedYear, selectedMonth, selectedDay, selectedHour, selectedMinute, 0, 0);
My AJAX request looks like this:
var updateRequest = jQuery.ajax({
url: app_path + "save_profile.php",
data: { 'user_id': this.userId,
'birth_date': this.birthDate.toUTCString(),
... },
type: 'POST',
datatype: 'json',
success: function(response, status) {
...
},
error: function (xhr, options, error) {
...
}
});
And here’s my PHP database query:
$query = "UPDATE user_profile
SET prof_gender = '".$user_gender."',
prof_diet_plan = (SELECT plan_id FROM diet_plans WHERE plan_name = '".$user_diet."'),
prof_activity_level = (SELECT level_id FROM activity_levels WHERE level_name = '".$user_activity."'),
prof_birth_date = '".$user_birthdate."'
WHERE prof_user_id = ".$user_id;
What’s the correct way to format the date so MySQL will accept it?