Если оператор else для jQuery AJAX не запущен - PullRequest
0 голосов
/ 22 сентября 2018

Когда я вставляю фрагмент и запускаю его при переполнении стека, он говорит: «$ is missing»!Однако единственной проблемой является оператор if и else, чтобы проверить, не является ли номер бронирования всем номером, не выполняется.Функция AJAX запускается, и поток переходит на сервер и сохраняет данные.Я запутался, есть ли что-то не так в этом коде?

clickme = function() {
  alert("hiiiiiii")
  var selected = $('input:checked');
  var chosen_emails = [];
  selected.each(function() {
    chosen_emails.push($(this).val());
  });

  var re = /[0-9]/;
  var booking_address = document.forms["contact"]["booking_address"].value;

  var booking_number = document.forms["contact"]["booking_number"].value;
  var booking_message = document.forms["contact"]["booking_message"].value;

  var booking_date = document.forms["contact"]["booking_date"].value;
  alert("booking address is" + booking_address + "booking_number is" + booking_number + "booking message is" + booking_message + "booking date is:" + booking_date);

  array = chosen_emails + "" //converting choosen_emails to string type 

  alert("choosen techies are:" + chosen_emails);

  var currentdate = new Date();
  var request_date = currentdate.getDate() + "/" +
    (currentdate.getMonth() + 1) + "/" +
    currentdate.getFullYear() + " @ " +
    currentdate.getHours() + ":" +
    currentdate.getMinutes() + ":" +
    currentdate.getSeconds();

  var user_email = "${user_email}";

  if (booking_number.length < 8) {
    alert("must not be less than 8 numbers");
  } else if (!re.test(booking_number)) {

    alert("Error: must not contain any characters!");
  } else {
    $(function() {
      $.ajax({ // defining the below function as ajax responsive//
        url: 'service_request', // the function that process the  mapped url name and matching type is going to receive the data//
        type: 'POST',
        data: {
          chosen_emails_1: chosen_emails[2],
          chosen_emails_2: chosen_emails[3],
          chosen_emails_3: chosen_emails[4],
          booking_address: booking_address,
          booking_number: booking_number,
          booking_message: booking_message,
          booking_date: booking_date,
          request_date: request_date,
          user_email: user_email
        }, // function to get the value from jsp page and send it to mapped class function//
        success: function(response) { // if the backend process is success then the function will run by getting the response as its parameter//
          alert(response.message);
        },
        error: function(response) {
          alert("there was an error processing your request");
        }
      });
    });
  }
}

//to set limit for number of checkboxes to be selected

$(document).ready(function() { //Its crucial that we are Wrap the code in ready() callback, so that the code (on change event handler) will be executed after DOM is finished loading (response data)
  $("#table").on("click", function() {
    var limit = 3,
      checkboxes = $(this).find("input:checkbox"),
      valid = checkboxes.filter(":checked").length >= limit;
    if (valid) {
      checkboxes.not(":checked").attr("disabled", valid);
      $('.container').show();
    }
  });
});
<div class="container" style="display: none;">
  <p> Enter your details to successfully complete the service request </p>
  <form id="contact" action="" method="post">
    <fieldset>
      <input placeholder="Your Address" type="text" tabindex="1" name="booking_address" required>
    </fieldset>
    <fieldset>
      <input type="text" tabindex="2" placeholder="Your number" name="booking_number" id="booking_number" required pattern="('^\\d+$')" title="Must contain only numbers" required/>
    </fieldset>
    <fieldset>
      <label for="datetime"> select your date and time</label>
      <input type="datetime" id='datetime' placeholder="select date and time" name="booking_date" tabindex="3" required>
    </fieldset>
    <fieldset>
      <textarea placeholder="Type your message here(optional) ...." tabindex="4" name="booking_message" required></textarea>
    </fieldset>
    <fieldset>
      <button name="submit" type="submit" onclick="clickme()" id="contact-submit">Submit</button>
    </fieldset>
  </form>
</div>
<div id="check-emails"></div>

1 Ответ

0 голосов
/ 22 сентября 2018

Ваше регулярное выражение соответствует строкам, которые содержат хотя бы одно число:

var re = /[0-9]/;
re.test('39583902'); // true
re.test('mostly letters but also 1 number'); // true
re.test('entirely letters'); // false

Инвертируйте логику вашего регулярного выражения и if условие:

var re = /[^0-9]/;
...
else if (re.test(booking_number)) {
  alert('Numbers only, please');
}

Вы также можете отбросить всепроверьте код из вашего обработчика кликов и позвольте браузеру обработать его:

$(document).ready(function() {
  $("#contact").on("submit", function(evt) {
    console.log("in the form's submit handler");
    evt.preventDefault();
    // Run your AJAX here
  });
});
label {
  display: block;
  margin: 0.5em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Enter your details to successfully complete the service request </p>
<form id="contact" action="" method="post">
    <label>
      Your Address
      <input placeholder="123 Anywhere St." type="text" tabindex="1" name="booking_address" required>
    </label>
    <label>
      Your number
      <input type="text" tabindex="2" placeholder="12345678" name="booking_number" id="booking_number" required pattern="^\d+$" minlength="8" title="Must contain only numbers" required>
    </label>
    <label>
      Select your date and time
      <input type="datetime-local" id='datetime' placeholder="2015-10-21T16:29" name="booking_date" tabindex="3" required>
    </label>
    <label>
      Message (optional)
      <textarea placeholder="Placeholders are for example data, not a prompt." tabindex="4" name="booking_message"></textarea>
    </label>
    <button name="submit" type="submit" id="contact-submit">Submit</button>
</form>

Я добавил атрибут minlength к номеру бронирования <input> и исправил его регулярное выражение проверки (HTML просто нужно содержимоеregex, и его управляющий символ - &; нет необходимости экранировать \d).

Браузер не отправит форму, которая не проверяет, поэтому вы можете поместить свой AJAX в формуОбработчик submit (не обработчик click кнопки отправки), и он будет работать только с действительными данными.Обязательно наберите preventDefault() для события, чтобы при отправке формы страница не перезагружалась.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...