0

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. I'm not showing the controller since the request doesn't even get there.

$(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!!!!");
    } 
  });      
 });  
});
Itzik Ben Hutta
  • 193
  • 2
  • 14
  • Is expected result to upload `File` object ? or `File` object property `name` ? – guest271314 Sep 20 '15 at 23:59
  • Not sure I understand what you mean. I have an input with type file and name filename. Either one I fetch I get the error, but the console.log("file") shows the correct filename. So there must be a problem with Ajax. Maybe It's not possible the way I'm trying to do it. – Itzik Ben Hutta Sep 21 '15 at 00:07
  • Is expected result to upload file name or `File` object ? `$('input[type=file]').val().split('\\').pop();` appear to be string , not `File` object – guest271314 Sep 21 '15 at 00:09
  • File object. How can I fetch it then? – Itzik Ben Hutta Sep 21 '15 at 00:12
  • Could fetch `File` object using `$('input[type=file]')[0].files` see http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload/ – guest271314 Sep 21 '15 at 00:17
  • Thanks. So I used FormData and appended the file name. My problem now is when I fetch the file name in the controller I don't get the real file name, I get this "C:\wamp\tmp\php7978.tmp". – Itzik Ben Hutta Sep 21 '15 at 02:01
  • See http://stackoverflow.com/questions/3945330/php-filestmp-name , http://php.net/manual/en/features.file-upload.php – guest271314 Sep 21 '15 at 02:19
  • Thanks. Got it to work. Now I need to see how to load the image without refresh, otherwise there is no point for the whole thing. – Itzik Ben Hutta Sep 21 '15 at 02:34
  • _"how to load the image without refresh"_ Why is page refreshed ? – guest271314 Sep 21 '15 at 02:39

0 Answers0