1

I call my_function on form submit. The function looks inside a text file for the number entered by the user in my_input. If this number does not exist, the function pops an alert and should stop form submit.

My problem: the alert is shown, but when I close it, the form gets submitted. What am I doing wrong? Why does my_function not return false?

function my_function() {

  $.get("http://www.example.com/file.txt", function(contents) {

    var my_number = document.getElementById("my_input").value;
    var hasString = contents.includes(my_number);
    if (hasString == false) {
      alert('Number does not exist in text file!');
      return false;
    }
  });

}

function function_one() {
  var my_number = document.getElementById("my_input").value;
  var pattern = /^(0|1|2)\d{5}$/;

  if (pattern.test(my_number)) {

    $("#cauta_c").val("wait..");
    $("#cauta_c").prop("disabled", true);
    $("#cauta_c").addClass("my_class");

    return true;
  }

  alert('not valid!');
  return false;

}
<form action="https://www.example.com/cgi-bin/script.cgi" 
      name="whatever" 
      id="whatever" 
      method="post" 
      onsubmit="return function_one() && my_function()" 
      autocomplete="off" 
      spellcheck="false" 
      autocorrect="off" 
      novalidate="novalidate">
nem035
  • 34,790
  • 6
  • 87
  • 99
Malasorte
  • 1,153
  • 7
  • 21
  • 45
  • Please show the rest of your code, specifically your form submit handler. – Jared Oct 12 '16 at 14:50
  • maybe === instead of == ? – MrEhawk82 Oct 12 '16 at 14:55
  • how do you call `my_function`? – Max Koretskyi Oct 12 '16 at 14:56
  • Maybe you should try to add the event of the form submitted as param to my_function and when condition is not accomplished, to call for `preventDefault()` method of event of form submitted. – Dez Oct 12 '16 at 14:59
  • 1
    Apart from the fact that your code has bad structure and presentation, your main mistake is that you call `return false;` inside of the `$.get()` callback. – Christophe Marois Oct 12 '16 at 15:01
  • 1
    @Malasorte, I don't think this question is an _exact_ duplicate. Your think that a browser will be waiting until you handler is `function(contents) {` is executed. But a browser doesn't wait. If you want, you can edit the question or create new one with a bit different example. Leave one function there `onsubmit='my_function()'` and ask why the form still gets submitted while the `my_function()` returns `false`. – Max Koretskyi Oct 12 '16 at 15:12

0 Answers0