O
O
Outsider V.2017-11-13 21:11:25
SQL
Outsider V., 2017-11-13 21:11:25

How to submit avatar along with registration form via AJAX?

I have a normal post request for a registration form:

function tryToRegister(login_window) {
    var name = $('[name="name"]').val();
    var password = $('[name="password"]').val();
    var password_confirmation = $('[name="password_confirmation"]').val();
    var email = $('[name="email"]').val();
    var recaptcha = grecaptcha.getResponse();
    var _token = $('[name="_token"]').val();
    $.post('/register', {
        'name': name,
        'password_confirmation': password_confirmation,
        'email': email,
        'password': password,
        'g-recaptcha-response': recaptcha,
        '_token': _token
    }, function (data) {
         // if ok
    }).fail(function (xhr, status, error) {
           // if error
    });
}


But in this form there is also a file upload:
<input type="file" name="avatar" class="registration-form__avatar__uploader__input">


I don’t understand how I can also attach an avatar image to the AJAX data, so that I can then read it in PHP as usual from the $_FILES array. Everywhere where file uploading via AJAX is described - just separately uploading files or uploading immediately when a file is selected, and I need to send a file along with a form, one request, one script.

PS Please do not judge strictly, I am a back-end developer who had to write the front.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey, 2019-08-22
@reaferon

SELECT *,  TIMESTAMPDIFF(SECOND, start_at, finish_at)
  AS 'SECONDS' FROM `task` ORDER BY SECONDS DESC

Thanks ISE73

D
Dmitry, 2017-11-13
@Audiophile

Good evening.
Just uploading an image via ajax will not work.
Use FormData and you'll be fine.
p.s.
Something like this:

function Testing(url, form){
      var file = '';
    var formdata = new FormData(form[0]);
    formdata.forEach(function(item, i, arr){
      console.log(i + ': ' + item + " array: " + arr)
      if(i == 'files'){
        formdata.append(item.name, item)
      }
    })

        $.ajax({
        	url: url,
        	type: 'POST',
        	processData: false,
            contentType: false,
        	data: formdata,
        	success: function(data){
        		console.log(data)
        	}
        })
  }

  $('#form-data').on('submit', function(e){
    e.preventDefault();
    var files = $(this).find('input:file')
    Testing('upload.php', $(this))
  })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question