Reputation: 23
I can't pass datetime mysql value to datetime local input field
MYSQL Data: 1995-10-29 08:00:00
Ajax:
function getTransaction(id){
$.ajax({
type:'POST',
dataType:'json',
data:{id:id},
url: 'queries/getTransactionInfo.php',
success:function(e){
$("#pickup_date").html((e[4]));
$("#return_date").text(e[5]);
}
});
}
php:
$select = $mysqli->prepare('SELECT * from tb_transaction where `id`=?; ');
$select->bind_param('i',$id);
if($select->execute()){
$result=$select->get_result();
$id=0;
while($row=$result->fetch_array()){
$data[]=$row['requestor'];
$data[]=$row['requestor_email'];
$data[]=$row['pickup_location'];
$data[]=$row['destination_location'];
$data[]=$row['from_date'];
$data[]=$row['to_date'];
$data[]=$row['purpose'];
$data[]=$row['no_passenger'];
}
echo json_encode($data);
}else{
}
Html:
<input type="datetime-local" class='form-control' id="pickup_date">
How can I pass it correctly? I tried using .val and .html but still not working also tried using Date.parse and still not working.
Upvotes: 2
Views: 1443
Reputation: 460
The format for datetime-local
is like 2018-06-07T00:00
with the T
delimiting the time. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
In PHP, you can use DateTime
class to format your time. https://www.php.net/manual/en/datetime.format.php
Here is an example:
<?php
$time = new DateTime('1995-10-29 08:00:00');
echo $time->format('Y-m-d\TH:i')
//Output is: 1995-10-29T08:00
?>
In your PHP code,
....
....
$timeFormat = 'Y-m-d\TH:i';
while($row=$result->fetch_array()){
$from_date = new DateTime($row['from_date']);
$to_date = new DateTime($row['to_date']);
$data[]=$row['requestor'];
$data[]=$row['requestor_email'];
$data[]=$row['pickup_location'];
$data[]=$row['destination_location'];
$data[]=$from_date->format($timeFormat);
$data[]=$to_date->format($timeFormat);
$data[]=$row['purpose'];
$data[]=$row['no_passenger'];
}
echo json_encode($data);
....
It will then already be in the correct format so no need to do anything to it in Javascript.
AJAX
....
....
success:function(e){
$("#pickup_date").val(e[4]);
$("#return_date").val(e[5]);
}
Upvotes: 1