Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
How to get the text value of a datepicker?

I am trying to get the text value of a datepicker so that I can store it in a MySQL database.

Here is a sample of my HTML code (index.php):

   <div class="col-xl-6">
       <input id="datepicker2" placeholder="Date">
   </div>

    <div class="col-xl-12">
        <a href="#form3" class="popup-with-form">
            <button type="submit" class="boxed-btn3" onclick="customFunction()">Next</button>
        </a>
    </div>

Here is the JavaScript code (within index.php):

    <script>

      function customFunction() {
       
          var DateOfBirth = document.getElementById("datepicker2").value;
           
          if (DateOfBirth != null && DateOfBirth !="") {
                $.post("insert.php", {DateOfBirth : DateOfBirth },function(response){
                    console.log(response);
                });
            }   
 
       }

   </script>

Here is the insert.php file code:

 <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "testdb";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
        $Date = isset($_POST['DateOfBirth'])?$_POST['DateOfBirth']:'';

    
    $sql = "INSERT INTO datepick (SinceDate) VALUES ('"$Date"')"; 
        
    
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
    ?> 

The issue I am having is that I am unable to get the text value of the datepicker. Does anyone know a solution to this?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Change the attribute in the button tag, right now is submit, change it for button.

<button type="button" class="boxed-btn3" onclick="customFunction()">Next</button>
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think the problem of the empty post in your insert.php script is the fact that your JS doesn't properly send the data to the php script. I played a bit with your example on my own dev environment and i managed to make it work.

The only thing i changed in your index.php is that i gave your button an id so i can call it from javascript and i moved the javascript code in a separate file. I've been running a content-security-policy for so long that i just can't leave inline js anymore.

index.php

<div class="col-xl-6">
       <input id="datepicker2" placeholder="Date">
   </div>

    <div class="col-xl-12">
        <a href="#form3" class="popup-with-form">
            <button id="submit-button" type="submit" class="boxed-btn3">Next</button>
        </a>
    </div>

    <script src="js.js"></script>

I will use native JS and with new ES6 synthax and will also remove your JS from inline event hanlers (better anyway). Also i will not be using the jQuery ajax but native javascript fetch. So i've put your js in a file called js.js

js.js

document.getElementById('submit-button').addEventListener('click', () => {
    // pick the value of the input
    const dateofBirth = document.getElementById('datepicker2').value;
    // same as yours
    if (dateofBirth != null && dateofBirth != '') {
        // Using the new modern fetch api to send the request
        fetch('insert.php', {
            headers: {
                // This is what was missing from your call
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            method: 'post',
            // Building the data to send, basically you need a key value pair, so i gave it a 'data' key and value - the value of the input
            body: new URLSearchParams({
                'date': dateofBirth
            })
        })
        .then(response => response.text())
        .then(text => {
            // log the response in the console, for debug
            console.log(text);
        })
    }
});

Now, your insert.php file. You are wide open to SQL Injection attack with the current insert, so i have made some changes to include prepared statements.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "testdb";
    
    // Create connection, no need to check if it succeeded, we will be extending the error reporting
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    
    $Date = isset($_POST['DateOfBirth']) ? htmlspecialchars($_POST['DateOfBirth']) : null;

    if ($date !== null) {
        // build the sql query for prepared statement
        $sql = "INSERT INTO datepick (SinceDate) VALUES (?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $Date);
        if ($stmt->execute()) {
            echo "New record created successfully";
        }
    }    
    $conn->close();
?> 
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda