K
K
Konstantin Lavrovsky2019-12-11 23:21:16
AJAX
Konstantin Lavrovsky, 2019-12-11 23:21:16

Why is formData not working?

Good night, faced with the task of uploading files (pictures) via ajax to the server directly in the database.
But, I have a problem in the browser console writes such an error Uncaught ReferenceError: formData is not defined .
Although I seem to be doing everything right:

$('#postnews').click(function(event) {
    event.preventDefault();
    var url = '...';
    var data = $('form#news__form').serialize();
    var file_data = $('#newsimg').prop('files');
    var form_data = new FormData();
    form_data.append('file', file_data);
    $.ajax({
      url: url,
      type: 'POST',
      dataType: 'text',
      data: {data: data, formData: formData},
      cache:false, // В запросах POST отключено по умолчанию, но перестрахуемся
        contentType: false, // Тип кодирования данных мы задали в форме, это отключим
        processData: false, // Отключаем, так как передаем файл
    })
    .done(function() {
      $('.successful').slideDown();
      setTimeout(function(){
        $('.successful').slideUp();
      }, 2500)
      $('#news__form')[0].reset();
    })
    .fail(function() {
      $('.nsuccessful').slideDown();
      setTimeout(function(){
        $('.nsuccessful').slideUp();
      }, 2500)
    });
    setTimeout(function(){
      location.reload();	
    }, 2650)
    
  });

Without formdata, everything worked and everything was sent to the database.
I don't know how to solve this error.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Web Dentist, 2019-12-11
@s1mypj

var form_data = new FormData();
...
data: {data: data, formData: formData},

Your variable is named differently.
Correct toformData: form_data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question