K
K
Kooper_pro2018-03-30 15:49:46
JavaScript
Kooper_pro, 2018-03-30 15:49:46

Why isn't Ajax working?

There is an authorization form

spoiler

<div class="auth_form">
  <div class="center_block">
    <div class="form_block">
      <form  id="login_form"  method="post" action="">
        <input name="login" type="text" class="input_txt"   placeholder="логин" required>
        <input type="password" name="pass" class="input_txt"  placeholder="пароль" required>
        <input type="submit" class="buttons" value="Войти" id="sends">
      </form>
    </div>
  </div>
</div>


get html content code with ajax
spoiler

$('#login_form').submit(function(e){
    e.preventDefault();
    $.ajax({
      url: "include/login.php",
      type: "POST",
      dataType: "JSON",
      data: $('#login_form').serialize(),
      beforeSend: function(response) {
      	$("#wait").css("display","table");
      },
      success: function(response) {
       	if (response!='Error!#159') {
      $(".input_txt").val("");
      $(".auth_form").css("display","none");
      $( ".admin_panel" ).empty();
      $( ".admin_panel" ).append(response);
       	}else{
       		alert("Не верные данные входа!");
      $(".input_txt").val("");
       	}
       	
      },
      error: function(response) {
        //обработка ошибок при отправке
     },
     complete: function(response) {
      	$("#wait").css("display","none");
      }
    });
});


The code comes inserted into the block.
Already in the received html response there is a form by which we send data to the server with a file:
spoiler

<form enctype="multipart/form-data" method="post" id="data_type" class="genform">
  <label class="label_st">Укажите данные</label></br>
  <input name="type_data_text" class="text_st" required placeholder="Данные" type="text">
  <input type="hidden" name="data_text_id" value="type_1">
  <input type="file" name="file_type" id="file_data" class="inputfile" required accept="image/*">
  <label for="file_data" id="lab1">Выберите файл...</label>
  <input type="submit" class="button_st" value="Добавить" id="but1">
</form>


The script sends data to the server, where the data is written to the database and a new request is formed, in the form of arrays with html code, where the key is the class of the block into which you want to insert data.
spoiler

$('.genform').submit(function(e){
  e.preventDefault();
  var $that = $(this),
  formData = new FormData($that.get(0)); 
  
  $.ajax({
    url: "include/login.php",
    type: "POST",
    dataType: "JSON",
    processData: false,
    contentType: false,
    data: formData,
    beforeSend: function(response) {
      $("#wait").css("display","table");
    },
    success: function(response) {
      for (key in response){
        $("div").each(function(i) {
          if ($(this).hasClass(key)) {
            $( this).empty();
            $( this).append(response[key]);  

          }
        });	
      			}
      		},
    error: function(jqXHR, exception) {
      console.log(jqXHR) ; 
    },
    complete: function(response) {
      $("#wait").css("display","none");
    }
    });
  $(this)[0].reset();
  $("#lab1").text("Выберите файл...");
});


But for some reason, the request from the files is not sent, instead the page is updated and nothing happens, the database is empty.
But if the html response from the authorization form is not received from the server, but is initially inserted. Does everything work fine? What is the subtlety?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2018-03-30
@Kooper_pro

$('html').on('submit', '.genform', function(e){
        // обработчик
    });

that's how it should work. the problem is that you have a second form - a dynamic element

L
leni_m, 2018-03-30
@leni_m

Most likely, when the browser loads your js script, the page is not yet on the page .genformand the browser is of this type: “What is written in the script at all? Some element with the genform class that is not on the page, but they want something from me. I will continue and will not even process this dregs."
But the benefit is the $(selector).on(event, more precise selector, function () {...}) construct. And for example in this case

$('body').on('submit', '.genform', function (){...})
The browser will say: "Oops! body is there - everything is in order. Let's hang this handler, and whether this genform is there or not - I don't care anymore."

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question