0

I am trying to upload an image with ajax and i am getting: Failed to load resource: the server responded with a status of 500 (Internal Server Error). Here is my ajax:

$('document').ready(function() {
    $('#uploadImage').change(function(){
        image = $('#uploadImage').val;
        token = $('#token').val();
        $.ajax ({
            type: 'POST',
            url: '/photo',
            data: { image , token },
            success: function(){

                $('.img-thumbnail').attr("src", 'images/new_image.png');
            }
        })
    })


});

Here is my route: Route::post('/photo', 'ShopsController@uploadPhoto');

This is my controller:

public function uploadPhoto(Request $request)
    {

        //Sets file name according to authenticated shop id
        $imageName = 'new_image.png';

        //Save file to public/images

        $img = Image::make($request->file('image'));
     $img->resize(380, 300)->save('images/' . $imageName, 60);
    }

And this is my form:

<form action="{{ action('ShopsController@store') }}" method="post" enctype="multipart/form-data">
    <input id="token" type="hidden" name="_token" value="{{ csrf_token() }}">
   <input id="uploadImage" class="btn btn-upload" type="file" name="image"> </form>
Nico Orfi
  • 173
  • 1
  • 11

1 Answers1

0

AJAX file upload is a bit more complicated than just getting the value attribute of you image element.

Read the first answer to this question here: jQuery Ajax File Upload

It uses the FormData object MDN:

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

though it's not supported by all browsers.

An easy jQuery ajaxFileUpload example here:http://www.sitepoint.com/image-upload-example/

Community
  • 1
  • 1
TurtleTread
  • 1,297
  • 2
  • 12
  • 23
  • Thank you for your answer. Now i checked that when i set a 'get' method it is going little further. So i think that the problem is that although i have set a 'post' route on laravel its behavior is like a get. Could you explain me this? – Nico Orfi Jan 31 '16 at 20:06
  • image = $('#uploadImage').val; This won't work. Images have different formats, each has its own encoding. image = $('#uploadImage').val simply won't retrieve the image. And your POST route is not behaving like a GET. because either you have a GET route defined or the default get method give you some default error instead of the internal error. – TurtleTread Jan 31 '16 at 20:14
  • Nvm i will find some other way. Btw thank you for that ajax lesson and for your answer. – Nico Orfi Jan 31 '16 at 20:17