Receive the value of a datepicker

Asked

Viewed 862 times

-1

I have a Picker date like this

$('#datepicker2').on('change', function() {
			console.log('Submiting form');
			console.log(this.value);
			$('#form1').submit();
			
		}).trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />

<form action="" name="form1" id="form1" onsubmit="return false" method="POST">
<input type="date" id="datepicker2" name="datepicker2" value="<?php echo date('Y-m-d'); ?>">

</form>

And I’d like to know how I can get the datepicker value to make a select. I use the onchange function because I don’t want to have a button to do Submit but when the user changes the datepicker date.

  • It is not enough to submit the form (removing the onsubmit Return false) and manipulate the data in your action?

  • If you take off the onsubmit Return false the page is in an infinite loop refreshing

1 answer

0

You need to adjust 3 things in your code:

  1. Configure datepicker to perform form Submit when user selects a date
  2. Set the attribute readonly in the input to prevent the user from entering invalid dates
  3. Prevent form Ubmit event with event.preventDefault() not to refresh the page and send the 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>

ajax.php file

<?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;

References

Reading suggestions

  • So far so good, but how can I use the $data variable to enter into the database? tells me that the index does not exist.

  • Update your question and include the query you are using to enter into the database so we can help you

  • My query is this &#xA;$query = "SELECT sum(dinheiro) as dinheiro, nome FROM gastos g, subcategorias s where s.codsubcategoria=g.codsubcategoria AND dataa='".$_POST['data']."' AND utilizador='".$_SESSION['email']."' group by s.codsubcategoria"; &#xA; I need to use the variable on the same page or the insertion is on the same page "Dashboard.php"

  • If you’re using the php example I posted above, change $_POST['data'] for $data can help you. The column name used in the query is dataa same (with 2 a) or would be data.

  • Yes I have also tried $data and says that the variable does not exist. Yes the column name is dated in the database

  • Remember that $_POST['data'] where data must be the same value used in the attribute name field. In your question is another value datepicker2. In that case it would be $_POST['datepicker2']

  • I copied what you suggested, also tried with datepicker2 and says Undefined index. Are you sure that the variable can be used on the same page?

  • You can try debugging print_r($_POST); exit; this will list the post array with their respective values

  • An empty array appears... I followed all the steps

  • In your question the action tag form is empty. If your code is empty also adjusts it to point to the page that processes the data. <form action="nome_do_arquivo.php">

  • So I need to put the action to the same page? And where do I put the code of ajax.php?

  • OK I already got this almost to give, there was a flaw in the form Submit in which the form name is Form1 and not form. But now when I change the date in the datepicker it does not update the data with the date I selected, it is always with today’s date

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.