R
R
Ruslan Website2021-08-29 07:45:44
AJAX
Ruslan Website, 2021-08-29 07:45:44

Why is ajax not returning a response?

This code worked

$(document).ready(function () {
    $("#ajax_form").submit(
        function () {
            sendAjaxForm('result_form', 'ajax_form', 'create-article.php');
            return false;
        }
    );
});

function sendAjaxForm(result_form, ajax_form, url) {
    jQuery.ajax({
        url: url, //url страницы (php/obr.php)
        type: "POST", //метод отправки
        dataType: "html", //формат данных
        data: jQuery("#" + ajax_form).serializeArray(), // Сериализуем объект
        success: function (response) { //Данные отправлены успешно
            result = JSON.parse(response);
            document.getElementById(result_form).innerHTML = result;
            console.log(response);
        },
        error: function (response) { // Данные не отправлены
            document.getElementById(result_form).innerHTML = "Ошибка. Данные не отправлены.";
        }
    });
}


And this one works, but not completely, does not return a response, the handler is the same. Those. when I add a file upload, the response from the server does not come.
$(document).ready(function () {
    $("#ajax_form").submit(
        function (event) {
            event.preventDefault();
            let form = $('#' + $(this).attr('id'))[0];
            let fd = new FormData(form);

            jQuery.ajax({
                url: "create-article.php", //Адрес страницы
                type: "POST", //Метод отправки
                data: fd,
                processData: false,
                contentType: false,
                success: function (response) { //Успешно
                    result = JSON.parse(response);
                    document.getElementById(result_form).innerHTML = result;
                },
                error: function (response) { //Ошибка
                    document.getElementById(result_form).innerHTML = "Ошибка";
                }
            });
        }
    );
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-08-29
@zkrvndm

Try like this:

$(function () {
  $("#ajax_form").submit(
    async function(event) {
      var form = new FormData(event.target);
      event.preventDefault();
      try {
        var response = await $.ajax({
          url: 'create-article.php',
          type: 'POST',
          data: form,
          processData: false,
          contentType: false
        });
        console.log("Ответ серввера:\n" + response);
        alert("Ответ серввера:\n" + response);
      }
      catch(err) {
        alert('Ошибка отправки, детали см. в консоли!');
        console.log('Не удалось отправить форму:');
        console.error(err);
      }
    }
  );
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question