0

Hello i am submitiing my form through ajax.

<form id="addProductForm" action="javascript:void(0)" enctype="multipart/form-data">
    <input type="hidden" id="productId">
        <div class="row">
            <label for="caption" class="col-md-4 col-form-label">Post Image</label>
            <input type="file" class="form-control-file" id="image" name="image">   
         </div>
    <div class="row ">
        <button type="submit" id="submitAddProduct" class="btn btn-primary mr-auto ml-auto" style="margin-top:15px;">Submit</button>
    </div>
</form>

This is the submit script

$('#submitAddProduct').click(function(e){
    e.preventDefault();
    
    var image = $('#image').val();

    $.ajax({
        type:'GET',
        url:'/submitAddProduct',
        async:false,
        data:{
            'image' : image,
        },
        success:function(response) {
            $('#productId').val(response.msg);
        }
    });

});

In my controller,

public function submitAddProduct(Request $request){
        $data = $request->validate([
            'image' => ['required','image']
        ]);

        public function submitAddProduct(Request $request){
        $data = $request->validate([
            'image' => ['required','image']
        ]);

        // dd(request('image')->store('uploads','public'));

        $imagePath = request('image')->store('uploads','public');

        $image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
        $image->save();

        $id = Products::insertGetId($data);

        if($id){
            $arr = array('msg' => $id);
        }
        return Response()->json($arr);
    }

        $id = Products::insertGetId($data);

        if($id){
            $arr = array('msg' => $id);
        }
        return Response()->json($arr);
    }

image val is something like C://fakepath//name; I want image to be uploaded to storage/uploads in my public folder.

But i am getting errors. 422 Unprocessable Entity

Please Help. Thank You

Shah Rukh
  • 291
  • 1
  • 10
  • Fyi, `dd(...)` ends your script, use `dump(...)` if you want it to continue running – brombeer Aug 25 '20 at 12:45
  • r u passing csrf token ? – Devsi Odedra Aug 25 '20 at 12:45
  • sir this is GET request, i thought we dont need csrf for that, and also i know about dd, it should show the path, but it isnt showing anything – Shah Rukh Aug 25 '20 at 12:48
  • Please have a look, i have edited the question, i actually want it to be saved in uploads – Shah Rukh Aug 25 '20 at 12:51
  • Try and look at the request being sent in the network inspector tab. It should tell you that the actual image file isn't being sent. – Daan Meijer Aug 25 '20 at 12:53
  • Request URL: http://127.0.0.1:8000/submitAddProduct?name=asfs&min_order=13&units_id=1&selections_id=2&subcategories_id=1&description=scad&image=C%3A%5Cfakepath%5CfibreGlass.jpg Request Method: GET Status Code: 422 Unprocessable Entity – Shah Rukh Aug 25 '20 at 12:54
  • Sorry if url isnt visible, `&image=C%3A%5Cfakepath%5CfibreGlass.jpg` – Shah Rukh Aug 25 '20 at 12:56

2 Answers2

0

My current guess would be that your image gets stripped from the request, because it is bigger than upload_max_filesize and post_max_size allow. Can you try posting a very small (<100kB) image?

My rationale for this is that, if the file is too big, it gets stripped. If it is stripped, the validation rules fail, thus resulting in a 422.

Edit: I just noticed you're working with GET as an HTTP verb. Files can only be sent using POST (and PUT and PATCH, but let's leave those out for now).

Daan Meijer
  • 1,324
  • 7
  • 12
  • 1
    Okay sir, i will try it with POST then – Shah Rukh Aug 25 '20 at 12:55
  • You will also not want to use `.val()`, but access the actual File object of that input. Check out https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – Daan Meijer Aug 25 '20 at 13:01
0

You are using GET to upload files which does not make any sense.

  1. change the route from get to post in the routes file.

  2. Change the ajax code to send POST rather than GET.

  3. include the CSRF token in the ajax request:

    • Using headers:

      1. Add the following html meta tag to head (if it does not exists already): <meta name="csrf-token" content="{{ csrf_token() }}">.
      2. Add the header to your ajax:
      $.ajaxSetup({
          headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      
    • Or simply, add the token as parameter in the request itself:

      $.ajax({
          type:'POST',
          ...
          data:{
          '_token' : {{ csrf_token() }},
          ...
      },
      
  4. That should do the trick!

Side note: try using named routes (easier to maintain), and I recommend using Axios.

By default, the resources/js/bootstrap.js file includes the Axios HTTP library which will automatically send this for you - Laravel docs

Ali
  • 21
  • 8