Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

IsaacBen's avatar

Upload image with Ajax

For quite a while I'm failing to upload images through Ajax. I get a 500 internal error which I think relates to the fact that Ajax doesn't recognize that It's an image. I'm using this syntax which works well for comments, and likes. Images is where I have the problem.

$(document).ready(function(){
  $(document).delegate(".send-image","click",function(e){ 
    e.preventDefault();
    var idval = this.id;
    var file =  $('input[type=file]').val().split('\\').pop();
    console.log(file);
    $.ajax({
      url: 'store',
      type: "post",
            beforeSend: function (xhr) {
            var token = $('meta[name="csrf_token"]').attr('content');
            if (token) {
                  return xhr.setRequestHeader('X-CSRF-TOKEN', token);
            }                
        }, 
        data: {'id': idval, 'filename': file},
        success:function(data){
          console.log(data);   
          
        },error:function(){ 
            console.log("error!!!!");
        } 
  });      
 });  
});
0 likes
7 replies
dharmendrajadon's avatar
Level 1

you need to use FormData()

Ex-

var id = $('#id').val();
var image = $('#image')[0].files[0];
new form = new FormData();
form.append('id', id);
form.append('image', image);
$.ajax({
    url: 'upload',
    data: form,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success:function(response) {
        alert(response);
    }
});

Use this code according to your requirements and it will send files to your controller;

In controller,

$id = \Input::get('id);
$image = \Input::file('image');

Boooooooooom...

5 likes
IsaacBen's avatar

@dharmendrajadon Thanks for the response. It seems to be the right way, but I'm still with the same stupid error. Do you see anything wrong here?

    var form = new FormData();
    var image = $('#image')[0].files[0];
    form.append('image', image);
    $.ajax({
      url: 'store',
      data: form,
      cache: false,
      contentType: false,
      processData: false,
      type: "post",
            beforeSend: function (xhr) {
            var token = $('meta[name="csrf_token"]').attr('content');
            if (token) {
                  return xhr.setRequestHeader('X-CSRF-TOKEN', token);
            }                
        }, 
         //{'filename': image.name},
        success:function(data){
          alert(data);
1 like
IsaacBen's avatar

Okay I have a problem with the url for some reason. I will debug that, and it will probably work.

IsaacBen's avatar

@dharmendrajadon Yeah, it's working now. The problem was actually with my request. Now I need to see how to present the image properly since I'm using masonry library.

Please or to participate in this conversation.