Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
¿Cómo obtener el valor de texto de un selector de fechas?

Estoy tratando de obtener el valor de texto de un selector de fechas para poder almacenarlo en una base de datos MySQL.

Aquí hay una muestra de mi código HTML (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>

Aquí está el código JavaScript (dentro de 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>

Aquí está el código del archivo insert.php:

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

El problema que tengo es que no puedo obtener el valor de texto del selector de fecha. ¿Alguien sabe una solución para esto?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Cambie el atributo en la etiqueta del botón, en este momento es enviar, cámbielo por el botón.

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

0

Creo que el problema de la publicación vacía en su secuencia de comandos insert.php es el hecho de que su JS no envía correctamente los datos a la secuencia de comandos php. Jugué un poco con tu ejemplo en mi propio entorno de desarrollo y logré que funcionara.

Lo único que cambié en su index.php es que le di a su botón una identificación para poder llamarlo desde javascript y moví el código de javascript en un archivo separado. He estado ejecutando una política de seguridad de contenido durante tanto tiempo que ya no puedo dejar js en línea.

índice.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>

Usaré JS nativo y con el nuevo synthax ES6 y también eliminaré su JS de los controladores de eventos en línea (mejor de todos modos). Además, no usaré jQuery ajax sino búsqueda nativa de javascript. Así que puse tu js en un archivo llamado 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); }) } });

Ahora, su archivo insert.php. Está completamente abierto al ataque de inyección SQL con la inserción actual, por lo que he realizado algunos cambios para incluir declaraciones preparadas.

 <?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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!