T
You need to adjust 3 things in your code:Configure datepicker to submit the form when user select a datepickerSetar the attribute readonly in input to prevent the user from entering invalid datesPrevent the form submit event with event.preventDefault() not to refresh on the page and send data via ajax$("#datepicker2").datepicker({
dateFormat: 'dd/mm/yy',
dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
nextText: 'Próximo',
prevText: 'Anterior',
/**
* @See http://api.jqueryui.com/datepicker/#option-onSelect
*/
onSelect: function (dateText) {
console.log(dateText);
// usar o this aqui dentro faz referência ao campo
//console.log($(this));
$(this).parents('form').submit();
}
});
$('#form1').on('submit', function (e) {
e.preventDefault();
var $this = $(this);
var data = $this.serialize();
var url = $this.attr('action');
// debug
console.log(data);
$.post(url, data, function (response) {
// debug
console.log(response);
alert('sucesso');
})
.fail(function () {
alert('Erro no ajax');
});
});<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- <input type="date" id="datepicker2" name="datepicker2" value="<?php echo date('Y-m-d'); ?>"> -->
<form action="ajax.php" name="form1" id="form1" method="POST">
<input type="text" id="datepicker2" name="datepicker2" value="13/06/2019" readonly>
</form>Archive ajax.php<?php
/**
A data virá no formato que o datepicker enviar
Nesse caso d/m/Y, Mysql trabalha no formato Y-m-d
*/
$data = $_POST['datepicker2'];
/**
Transforma a data para Y-m-d
Você poderia fazer isso com a classe DateTime também
*/
$data = join('-', array_reverse(explode('/', $data)));
/**
TO DO
Connectar no banco
Preparar a query
Obter o resultado da query
Retornar o resultado para o ajax
*/
echo 'Data recebdida e já transformada no formado do mysql'. $data;
ReferencesjQuery datepicker http://api.jqueryui.com/datepicker/#option-onSelect jQuery https://api.jquery.com/jquery.post/ jQuery https://api.jquery.com/serialize/ jQuery https://api.jquery.com/event.preventDefault/#event-preventDefault W3C https://www.w3schools.com/tags/att_input_readonly.asp docReading suggestions https://pt.stackoverflow.com/questions/390661/submit-de-form-somente-com-a-tecla-enter-sem-bot%C3%A3o-n%C3%A3o-funciona/390741#390741 PHP https://www.php.net/manual/pt_BR/book.pdo.php PHP functions https://www.php.net/manual/pt_BR/ref.json.php