11

Laravel view:

<form  enctype="multipart/form-data" method="post" name="imagesform" id="imagesform" >
    <input type="hidden" name="_token" value="{{ csrf_token()}}">
    <div>
        <label id="show" for="files" class="button">Upload photo</label>
        <input id="files" name="images" style="visibility:hidden;" type="file">
    </div> 
    <button type="submit"  class="save" id="saveImage" style="border-radius: 8px; padding: 5px 15px;">SAVE</button>
</form>

This is my code for uploading images(it takes place inside my bootstrap model).When I upload the image,and click on the submit button,the image should inserted into db and the same should be retrieved and displayed on the view page.

Ajax code:

$("#saveImage").click(function(e){
    // var formdata=new FormData($("#imagesform")[0]);
    //alert(formdata);
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });
    $.ajax({
        url: 'saveImages/{{$dataId}}',
        type: 'POST',
        data:new FormData($("#imagesform")),
        success: function (data) {
            alert(data)
        },
        cache: false,
        processData: false
    });
    return false;
});

This is the ajax code,I have tried.But the alert of formdata shows [object FormData] and browser console shows Method not allowed exception

Laravel Route:

Route::post('saveImages/{dataId}',['as' => 'saveImages','uses'=>'priceDetails@saveImages']);

Controller:

public function saveImages(Request $imagesform,$dataId)
{
    if (Input::hasFile('images'))
    {
        $name  = $this->getImageId().".".$imagesform->file('images')->getClientOriginalExtension();   

        $image = $imagesform->file('images');        
        $resize = Image::make($image)->resize(700, 300)->encode($imagesform->file('images')->getClientOriginalExtension());
        $hash = md5($resize->__toString());

        $path = "public/" . $name;
        Storage::put($path, $resize->__toString());
    }
    $insertImages=new photosModel;
    $insertImages->imagesid=$this->getimagesId();
    $insertImages->deviceCategoryId=$dataId;
    $insertImages->uploadedImages=$name;
    $insertImages->save();
    return $this->formImages($dataId);

}

public function formImages($dataId){
    $dataId=$dataId;
    $images=photosModel::all();
    return view('addProductDetails1')->with('images',$images)->with('dataId',$dataId);
}
Haseeb Ibrar
  • 337
  • 5
  • 18

2 Answers2

6

To upload files via AJAX you need to use XHR Level 2. The FormData class needs a HTMLFormElement in the constructor if you want to send its key-value.

You should use:

new FormData( document.getElementById('imagesform') );

Also you could use with jQuery:

new FormData( $("#imagesform").get(0) )

Check my answer in another similar question to get more information.

UPDATE: Seeing your comments your problem is with the Laravel route too. If the error code is 500 and it is showing the message "Method not allowed" you need to check your routes in routes/web.php. Please put here the stacktrace of the error and your route file (use pastebin or similar).

SnakeDrak
  • 3,406
  • 4
  • 28
  • 41
  • priceDetails is my controller name Sir –  Aug 30 '17 at 09:06
  • line in the routes file?? –  Aug 30 '17 at 09:08
  • I apologize I didn't see your question well. Please could you put here the error with stacktrace? – SnakeDrak Aug 30 '17 at 09:12
  • Route::post('saveImages/{dataId}',['as' => 'saveImages','uses'=>'priceDetails@saveImages']); –  Aug 30 '17 at 09:13
  • To localize the problem we need to check step by step. The first put here the error message with the stacktrace (the error 500). The second step is check if the app is entering on the method of your controller (debug it or put a simple var_dump). The most probably will be it is not entering in the method so maybe the problem is with the routes files. Put here all routes please (use pastebin or similar). – SnakeDrak Aug 30 '17 at 09:16
  • But I don't see the error in your screenshot. Check the storage/logs/laravel.log. A stacktrace is similar to [that](https://devmarketer.io/wp-content/uploads/2016/07/laravel-5-error-page-1024x622.png). – SnakeDrak Aug 30 '17 at 09:20
  • #12 /var/www/html/AdminPanel/app/Http/Controllers/priceDetails.php(405): Illuminate\Database\Eloquent\Model->save() –  Aug 30 '17 at 09:38
  • #8 /var/www/html/AdminPanel/app/Http/Controllers/priceDetails.php(405): Illuminate\Database\Eloquent\Model->save() –  Aug 30 '17 at 09:39
  • Please, copy-paste the entire stacktrace (from #1 to #XX) and put it in some file (pastebin, google drive). – SnakeDrak Aug 30 '17 at 09:40
  • here includes my log file –  Aug 30 '17 at 09:54
  • this is what I'm getting now –  Aug 30 '17 at 10:03
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153227/discussion-between-pedro-gamez-and-nishanthi). – SnakeDrak Aug 30 '17 at 10:07
4

I was able to solve a similar problem by Frankensteining various suggestions from here. That link has a pile of really good information. You need to assign some options in the ajax call to false. In any case this is what worked for me:

HTML

<input name="image" type="file" id="image">

Javascript

data = new FormData();
    jQuery.each(jQuery('#image')[0].files, function(i, file) {
        data.append('image', file);
    });

$.ajax({
    url: "submit/ajax",
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    data: data,
    success: function(response)
       {
          // Display your uploaded image on the page
       }
    });

PHP

Image::make($_FILES['image']['tmp_name']) >save("$myImageDirectory/$newImagegName");
Birdtime
  • 41
  • 3