1

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 = "";
}

2
  • you should try what you are getting in code. then assign it to data by key and value. Commented Mar 22, 2017 at 10:17
  • when you want data at database.php why are you using alarm.php in ajax callback? Commented Mar 22, 2017 at 10:18

1 Answer 1

1

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks the data: { code: code } worked fine, I already had the other part set up. Now working all ok

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.