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

81
Vistas
Sending function sent data to php file by ajax

I am trying to send data to a database.php file by ajax. My Index file has a form which will collect a 4 digit input then sends to a js function which sends the data to my db file. At the moment the Db file is being called because I get a result in the console but the 4 digit key is not being sent. I expect I have done something wrong with the ajax script.

Any help please

function addCode(key) {
  var code = document.forms[0].code;
  if (code.value.length < 4) {
    code.value = code.value + key;
  }
  if (code.value.length == 4) {
    document.getElementById("message").style.display = "block";
    setTimeout(alarm, 1000, code.value);
  }
}

function alarm(code) {
  $.ajax({
    method: "POST",
    url: "alarm.php",
    data: code,
    cache: false,
    success: function(responseText) {
      console.log(responseText) // show returned text in console
    }
  })
  emptyCode();
}

function emptyCode() {
  document.forms[0].code.value = "";
}

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The issue is because you're just sending the value by itself with no key. To fix this you could provide data with an object that will be form encoded when the request is sent:

data: { code: code },

Then in your PHP code you can retrieve the posted value by its key:

$code = $_POST['code'];
about 4 years ago · Santiago Trujillo 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