CodeIgniter 4 Jquery Ajax File Upload

Well, because its not a tutorial but just my notes I’ll not talk to much.

Something that make it diferent with CI3 or file uploading without ajax is just on the ajax parameters, and controllers. (Assume you allready know about how working with CI4 – model and etc.)

Jquery Ajax

      $('#form').on('submit', function(e) {
          e.preventDefault();
          var data = new FormData(this);
          data.append("something_var", $('#something_id').val());
          $.ajax({
             url: $(this).attr('action'),
             enctype: 'multipart/form-data',
             type: 'POST',
             processData: false,
              contentType: false,
             data: data,
             dataType: 'json',
             success: function(result) {
                if (result.error == 'null') {
                  //do anything what you want after ajax success.
                } else {
                   $.each(result.error, function(i, log) {
                      $('[name="'+i+'"]').addClass('is-invalid');
                      $('#error_'+i).text(log);
                   });
                }            
             },
             error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus + errorThrown);
             }
          });
       });

In above code I show you how to create file uploading through ajax post request. As you know, if we working with file uploading through ajax, we should use POST request, its not acceptable if we using Get.

The, the important thing is about form data, we need to use fromData() beside form_open_multipart() or enctype multipart, because its using ajax.

Next important thing is if you need more params you should append it because if not the form data just called the file value.

Just follow my code above you’ll working fine.

Retrieving file input in Controller

if (!empty($_FILES['image']['name'])){
	$file = $this->request->getFile('image');
	$file_name = $file->getRandomName();
	$file->move('path/dir/', $file_name); 
}else{
	$file_name = '';
}

Assumed that you want to retrieve the uploaded file name then send it to database, before we setup params you need to do samething like I did in above code.

First, I checked is file name exist or not, its important because when I trying to using CI helper its not working as I want.

When the file is exist, then I use file uploading class to geting the file and using getRandomName() function to setup the new name. You can do whatever do you want for the name.

Then, its important to do move() the file to path/dir that you want, so it can be uploaded.

Note: For your attention that I assumed you have some knowledge working in CI4, then you will understand about it.