V
V
Vladimir2018-03-06 08:42:02
JavaScript
Vladimir, 2018-03-06 08:42:02

How to do error handling with Ajax?

Hello. Help to deal with Ajax, please. Namely, with an error handler. The form works, everything is sent. But I don't know how to do error handling. Wouldn't want to use the validate plugin.
Here is the code

<form action="<?=POST_FORM_ACTION_URI?>" method="POST" id="callback" name="callback">

  <div>
    <div>Ваше имя<span>*</span></div>
    <input type="text" name="author" value="" >
    <div class="form__error">Нужно заполнить!</div>
  </div>
  
  <div>
    <div>Номер телефона<span>*</span></div>
    <input type="text" name="phone" value="" >
    <div class="form__error">Нужно заполнить!</div>
  </div>					
  
  <div class="form__buttons">
    <input type="submit" class="form__submit" name="submit">
  </div>	
</form>

<script>
  $(document).ready(function() {
    $('form').on('submit', function(){
       var formID = $(this).attr('id');
       var formNm = $('#' + formID);
       if (formID == 'callback') {
       $.ajax({
        url: '/include/send_callback.php',
        type: 'post',
        data: formNm.serialize(),
        success: function(data){
          $(formNm).html(data);
        }
       });
         return false;
      };
    });
   });
</script>

I need to do this if the Name (Phone) field in the New block is not <div class="form__error">Нужно заполнить!</div>
filled<div class="form__error is active">

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ink, 2018-03-06
@AskMy

and the usual required is not an option?
https://codepen.io/topicstarter/pen/ddBKym

B
berzhikeev, 2018-03-06
@berzhikeev

On submit. the form can run a standard check (valid, from the browser), error highlighting will also be native (standard text "Fill in the field"). You can check like this

<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
    var inpObj = document.getElementById("id1");
    if (!inpObj.checkValidity()) {
        document.getElementById("demo").innerHTML = inpObj.validationMessage;
    }
}
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question