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

Edris899's avatar

How to fetch data from a ajax post request in the controller? Getting no data

Hi there,

I am building a illustration & album website in Laravel 5.6. I want to move a picture from a album to a different album with ajax.

The idea is to first select a picture with a checkbox on it. Then click on a button that toggles a bootstrap modal popup. Choosing the or selecting 1 album to move to. Then hitting the submit button.

The problem is that I don't get the data from the jquery ajax request. Only getting this response back

array:2 [▼
  "_method" => "POST"
  "_token" => "PURBuZhwRdDqMoVAQwoseoZsffQC2e6N2DDqpiYB"
]

This is the html code.

<form data-toggle="validator" action="{{route('users.photos.movePhotosToAlbumAjax')}}" method="post">
   {{method_field('POST')}}
   @csrf
   <div class="form-group">
      <label for="exampleFormControlSelect1">Choose a album</label>
      <select class="form-control" id="chosenAlbum">
         @foreach($albums as $album)
         <option id="{{$album->id}}" value="{{$album->id}}">{{$album->name}}</option>
         @endforeach
      </select>
   </div>
   <div class="row text-center">
      <div class="col-lg-6 offset-lg-3">
         <input data-token="{{ csrf_token() }}" id="moveIllustrationSubmit" type="submit" class="btn btn-success" value="Move Illustration"/>
      </div>
   </div>
</form>

This is the code in the controller.

public function movePhotosToAlbumAjax(Request $request){
        $data = $request->all();
        dd($data);
        return response()->json(['success'=>'Got Simple Ajax Request.']);;
    }

And this is the jquery.

$("#moveIllustrationSubmit").on("click", function() {
    $("input:checkbox:checked").each(function() {
        var $input = $(this);
        var photo_id = $input.attr("id");
        //console.log("Id: " + $input.attr("id") + " Value: " + $input.val());
        $("#chosenAlbum").change(function() {
            var albumId = $(this).find('option:selected').attr('id');

            //var albumId = $("#chosenAlbum").find('option:selected').attr('id');
            $.ajax({
                type: "post",
                dataType: 'JSON',
                url: '/users/photos/movePhotosToAlbumAjax/',
                data: {
                    "photo_id": photo_id,
                    "albumId": albumId,
                    _method: 'post'
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    console.log("de response terug");
                    console.log(response);
                    //$('#photo-' + url_id).remove();

                },
                error: function(qXHR, textStatus, errorThrown) {
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
        });
    });
});

This is the route.

    Route::post('users/photos/movePhotosToAlbumAjax/','AlbumsController@movePhotosToAlbumAjax')->name('users.photos.movePhotosToAlbumAjax');

Got any ideas? Thanks in advance.

0 likes
23 replies
Cronix's avatar

You don't prevent the default click event of your submit button, so it's actually submitting the html form, which doesn't have the photo_id and albumId form attributes set since you retrieve those using data properties and id's.

Change the first line to

$("#moveIllustrationSubmit").on("click", function(e) {
    e.preventDefault(); // prevent the form submission

and you can change to this

var albumId = $(this).val(); // just use the value of the selected element

and get rid of the id's on your options.

In your data parameters, you also don't need

_method: 'post'

Since this is an ajax request, in the controller you should return json unless you want to see a blob of all of the javascript that dd() sends...

return response()->json($data);
Edris899's avatar

Hi @Cronix

I changed the javascript code and code in the controller. But now it doesn't submit the form after clicking. Nothing happens.

This is the jquery.

  $("#moveIllustrationSubmit").on("click", function(e) {
     e.preventDefault(); // prevent the form submission
     $("input:checkbox:checked").each(function() {
         var $input = $(this);
         var photo_id = $input.attr("id");

         $("#chosenAlbum").change(function() {

             var albumId = $(this).val(); // just use the value of the selected element


             $.ajax({
                 type: "post",
                 dataType: 'JSON',
                 url: '/users/photos/movePhotosToAlbumAjax/',
                 data: {
                     "photo_id": photo_id,
                     "albumId": albumId
                 },
                 headers: {
                     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                 },
                 success: function(response) {
                     console.log("de response terug");
                     console.log(response);
                     //$('#photo-' + url_id).remove();

                 },
                 error: function(data) {
                     console.log(data)
                 }
             });
         });
     });
 });

About the data. I need the photo id thats selected and the selected newalbum id. Those I need to get transfered via ajax.

Cronix's avatar

I don't understand what you're trying to do here.

$("input:checkbox:checked").each(function() {

Why would you submit a separate ajax request for every checked checkbox? And where are these checkboxes?

Edris899's avatar

Hahah Cronix I am trying bro, I am trying . Well the idea behind is to check which photos is checked en get those ids. So if 2 photos are checked then it should move those 2 to the selected album from the selection menu/option.

Edris899's avatar

Sorry the checkboxes are used by this html.

<div class="row">
   @foreach($photosProcessed as $photoProcessed)
   <div class="col-lg-2" id="photo-{{ $photoProcessed->id }}">
      <div class="content" id="content" >
         <a id="overlay" href="{{route('users.photos.show',$photoProcessed->id)}}">
            <div class="content-overlay">
               <div class="col-lg-2">
                  <label class="checkbox_custom">
                  <input type="checkbox" name="checkbox_custom_a" id="{{$photoProcessed->id}}">
                  <span class="checkmark"></span>
                  </label>
               </div>
            </div>
            <img class="content-image" src="/storage/user-content/{{$user->hash}}/{{$photoProcessed->hash}}/{{$photoProcessed->thumbnailhash}}/{{$photoProcessed->photo}}" alt="{{$photoProcessed->title}}">
            <div class="content-details fadeIn-bottom">
               <h3 class="content-title">{{$photoProcessed->title}}</h3>
               <p class="content-text">{{$photoProcessed->description}}</p>
            </div>
         </a>
      </div>
      <br>
   </div>
   @endforeach
</div>
Cronix's avatar

This would be a lot simpler if those checkboxes were actually a part of your form, and you named them using array syntax, like

<input type="checkbox" name="checkbox_custom_a[]" value="{{$photoProcessed->id}}">

and gave them a value instead of an id

Edris899's avatar

Hmm oke oke. So you mean to rearrange the html?

Cronix's avatar

Probably. It's hard for me to visualize everything with chunks of code here and there, especially your view. But what I can say is how you have it now won't work, and will take a lot more code to make it work.

photo_id should be an array of multiple id's, the photos that were "checked", correct? You want to send multiple photo id's, and one album id?

Edris899's avatar

Yeah. I understand. I am trying to make something in that model aka form. To select there the photo(s) and the album.

Cronix's avatar

please show your whole view file.

Edris899's avatar

Aright i have copied some html to the modal where the form is. To select there the photo(s) to move and to select the album.

This is the whole view file.

@extends('layouts.app') 
@section('content')
<br>
<div class="container-fluid">
   <div class="row">
      <div class="col-lg-12">
         <div class="jumbotron jumbotron-fluid">
            <div class="row text-center">
               <div class="col-lg-6 offset-lg-3">
                  <h4>Album: {{$album->name}}</h4>
               </div>
            </div>
            <br>
            <div class="row">
               <div class="col-md-2 offset-md-1">
                  <a class="btn btn-secondary" href="{{route('users.photos.home')}}" role="button">Go Back</a>
               </div>
               <div class="col-lg-6 offset-lg-0">
                  <div class="input-group input-group-lg mb-3" style="margint-top:-30px;">
                     <input type="text" class="form-control" placeholder="Search your illustrations" aria-label="Search your illustrations" aria-describedby="button-addon2">
                     <div class="input-group-append">
                        <button class="btn btn-outline-secondary" type="button" id="button-addon2">Search</button>
                     </div>
                  </div>
               </div>
            </div>
            <br>
            <div class="row">
               <div class="col-lg-8 offset-lg-3">
                  <button class='btn btn disabled' style='background-color:#cfd8dc;'>
                  <i class="fa fa-user-friends grayText"></i> Share
                  </button>
                  <button class='btn btn' style='background-color:#cfd8dc;'>
                  <i class="fas fa-check-double grayText"></i> Select All
                  </button>
                  <button class='btn btn' style='background-color:#cfd8dc;' data-toggle="modal" data-target="#addIllustration">
                  <i class="fas fa-images grayText"></i> Add Illustration
                  </button>
                  <button class='btn btn moveIllustration' style='background-color:#cfd8dc;' data-toggle="modal" data-target=".bd-example-modal-lg">
                  <i class="fas fa-images grayText"></i> Move Illustration
                  </button>
                  <button class='btn btn' style='background-color:#cfd8dc;' id="delete" type="submit" data-token="{{ csrf_token() }}">
                  <i class="fas fa-trash grayText"></i>
                  </button>
                  @if($photosProcessedCount == 1 )
                  <h5 class="grayText float-right">{{$photosProcessedCount}} Illustration Found</h5>
                  @else
                  <h5 class="grayText float-right">{{$photosProcessedCount}} Illustrations Found</h5>
                  @endif
               </div>
            </div>
            <div class="row">
               <div class="col-lg-8 offset-lg-3">
                  <h5 class="grayText float-right">{{$photosProcessedCount}}  Processed</h5>
               </div>
            </div>
            <div class="row">
               <div class="col-lg-8 offset-lg-3">
                  <h5 class="grayText float-right">{{$photosNotProcessedCount}} Not Processed</h5>
               </div>
            </div>
            @if($photosNotProcessedCount != 0)
            <div class="row text-center">
               <div class="col-lg-6 offset-lg-3">
                  <i class="fas fa-exclamation fa-2x"></i>
                  <h5>You have illustrations to be processed.</h5>
               </div>
            </div>
            <div class="row text-center">
               <div class="col-lg-6 offset-lg-3">
                  <a name="" id="" class="btn btn-success" href="{{route('users.photos.viewNonProcessed',$album->id)}}" role="button">Process Illustrations</a>
               </div>
            </div>
            @endif
            <div class="row">
               <div class="col-lg-6 offset-lg-3">
                  <hr>
               </div>
            </div>
            <br>
            <div class="row">
               @foreach($photosProcessed as $photoProcessed)
               <div class="col-lg-2" id="photo-{{ $photoProcessed->id }}">
                  <div class="content" id="content" >
                     <a id="overlay" href="{{route('users.photos.show',$photoProcessed->id)}}">
                        <div class="content-overlay">
                           <div class="col-lg-2">
                              <label class="checkbox_custom">
                              <input type="checkbox" name="checkbox_custom_a" id="{{$photoProcessed->id}}">
                              <span class="checkmark"></span>
                              </label>
                           </div>
                        </div>
                        <img class="content-image" src="#" alt="{{$photoProcessed->title}}">
                        <div class="content-details fadeIn-bottom">
                           <h3 class="content-title">{{$photoProcessed->title}}</h3>
                           <p class="content-text">{{$photoProcessed->description}}</p>
                        </div>
                     </a>
                  </div>
                  <br>
               </div>
               @endforeach
            </div>
         </div>
      </div>
   </div>
</div>
<div class="modal fade" id="addIllustration" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
   <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle">Add Illustrations</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
            </button>
         </div>
         <div class="modal-body">
            <div class="row">
               <div class="col-lg-12">
                  <div id="image_preview"></div>
                  <br>
                  <form action="{{ route('users.photos.storePhotosToAlbum', $album->id) }}" method="post" enctype="multipart/form-data">
                     {{ csrf_field() }}
                     <input type="file" id="uploadFile" name="uploadFile[]" multiple/>
                     <input type="submit" class="btn btn-success" name='submitImage' value="Upload Image"/>
                  </form>
                  <br/>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
//This is the modal for the movePhotosToAlbum
<div class="modal fade bd-example-modal-lg" id="moveIllustration" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
   <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle">Move Illustrations</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
            </button>
         </div>
         <div class="modal-body">
            <div class="row">
               <div class="col-lg-12">
                  <form data-toggle="validator" action="{{route('users.photos.movePhotosToAlbumAjax')}}" method="post">
                     {{method_field('POST')}}
                     @csrf
                     <div class="form-group">
                        @foreach($photosProcessed as $photoProcessed)
                        <div class="col-lg-4" id="photo-{{ $photoProcessed->id }}">
                           <div class="content" id="content" >
                              <a id="overlay" href="{{route('users.photos.show',$photoProcessed->id)}}">
                                 <div class="content-overlay">
                                    <div class="col-lg-2">
                                       <label class="checkbox_custom">
                                       <input type="checkbox" name="checkbox_custom_a[]" value="{{$photoProcessed->id}}">
                                       <span class="checkmark"></span>
                                       </label>
                                    </div>
                                 </div>
                                 <img class="content-image" src="#" alt="{{$photoProcessed->title}}">
                                 <div class="content-details fadeIn-bottom">
                                    <h3 class="content-title">{{$photoProcessed->title}}</h3>
                                    <p class="content-text">{{$photoProcessed->description}}</p>
                                 </div>
                              </a>
                           </div>
                           <br>
                        </div>
                        @endforeach
                     </div>
                     <div class="form-group">
                        <label for="exampleFormControlSelect1">Choose a album</label>
                        <select class="form-control" id="chosenAlbum">
                           @foreach($albums as $album)
                           <option id="{{$album->id}}" value="{{$album->id}}">{{$album->name}}</option>
                           @endforeach
                        </select>
                     </div>
                     <div class="row text-center">
                        <div class="col-lg-6 offset-lg-3">
                           <input data-token="{{ csrf_token() }}" id="moveIllustrationSubmit" type="submit" class="btn btn-success" value="Move Illustration"/>
                        </div>
                     </div>
                  </form>
                  <br/>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
</div>
@endsection
@section('scripts')
<script type="text/javascript">
   $( document ).ready(function() {
       $('.moveIllustration').addClass('disabled');
   
       
       $( "input" ).change(function() {
           var $input = $( this );
           var checkboxState = $input.prop("checked");
   
           if(checkboxState == true){
               $(this).closest(".content").addClass("checked details");
               //$(this).find("#moveIllustration").removeClass("disabled");
               $('.moveIllustration').removeClass('disabled');
           }
   
           if(checkboxState == false){
               $(this).closest(".content").removeClass("checked details");
               $('.moveIllustration').addClass('disabled');
   
           }
       }).change();
   
   
       //$("#chosenAlbum").change(function() {
       //    var albumId = $(this).find('option:selected').attr('id');
       //    console.log(albumId);
       //  });
   
       
       $( "#moveIllustrationSubmit" ).on( "click", function(e) {
           e.preventDefault(); // prevent the form submission
           $("input:checkbox:checked").each(function () {
               var $input = $( this );
               var photo_id = $input.attr("id");
               console.log("benaan0");
               //console.log("Id: " + $input.attr("id") + " Value: " + $input.val());
               $("#chosenAlbum").change(function() {
                   //var albumId = $(this).find('option:selected').attr('id');
                   var albumId = $(this).val();
                   console.log('benaan');
                   
                   //var albumId = $("#chosenAlbum").find('option:selected').attr('id');
                   $.ajax({
                       type: "post",
                       dataType: 'JSON',
                       url: '/users/photos/movePhotosToAlbumAjax/',
                       data: {},
                       headers: {
                           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                       },
                       success: function (response) {
                           console.log("de response terug");
                           console.log(response);
                           //$('#photo-' + url_id).remove();
                       
                       },
                       error: function (data) {
                           console.log(data)
                       }
                   });
             });
           });
       });
       
   
   
   
   
   
   
       $( "#delete" ).on( "click", function() {
           var confirmation = confirm("Are you sure you want to remove the Illustration(s)?");
   
           if (confirmation)  {
               $("input:checkbox:checked").each(function () {
                   var $input = $( this );
                   //console.log("Id: " + $input.attr("id") + " Value: " + $input.val());
                   
                   var _id = $input.attr("id");
                   
                   
                   $.ajax({
                       type: "post",
                       url: '/users/photos/destroy/' + url_id,
                       data: {"id": url_id , _method: 'delete'},
                       headers: {
                           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                       },
                       success: function () {
                           
                           $('#photo-' + url_id).remove();
                       
                       },
                       error: function (data) {
                           //console.log('Error:', data);
                       }
                   });
               });
           }
       });
   
       
   });
   
   
</script>
@endsection
Cronix's avatar
Cronix
Best Answer
Level 67

I'll just give you the pseudocode.

// give form an id
<form data-toggle="validator" action="{{route('users.photos.movePhotosToAlbumAjax')}}" method="post" id="myform">

// create the checkboxes, using array syntax for the name and giving them a value
@foreach($photosProcessed as $photoProcessed)
    <input type="checkbox" name="photo_id[]" value="{{$photoProcessed->id}}">
@endforeach 

// create the select element, giving it a name and the options values
<select class="form-control" name="album_id">
    @foreach($albums as $album)
         <option value="{{$album->id}}">{{$album->name}}</option>
    @endforeach
</select>

// submit button
<button type="submit" class="btn btn-success" value="Move Illustration">Move Illustration</button>

</form>

javascript

<script>
$(function() {
    $("#myform").on("submit", function(e) {
        e.preventDefault(); // prevent the form submission
        $.ajax({
            type: "post",
            dataType: 'JSON',
            url: '/users/photos/movePhotosToAlbumAjax/',
            data: $('#myform').serialize(), // serialize all form inputs
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                console.log("de response terug");
                console.log(response);
            },
            error: function(data) {
                console.log(data)
            }
        });
    });
});
</script>

and in the controller,

$request->photo_id; // array of all selected photo id's
$request->album_id; // id of album
2 likes
jlrdw's avatar

Seems you are kind of new to this you should take some basic tutorials first on jQuery ajax.

And some tutorials on how to deal with checkbox data.

As an example were you aware that if a checkbox is not checked, nothing gets passed in the post request.

Really by time someone starts using laravel they should be well-versed in this other stuff. or at least familiar with it.

So it's just my suggestion to learn a little more Basics first.

I'll just give you the pseudocode

But that's not copy and paste ready to go.

Edris899's avatar

@Cronix getting the following error in the console of chrome.

GET http://www.test.nl.test/users/photos/movePhotosToAlbumAjax 405 (Method Not Allowed)
Cronix's avatar

somehow you're sending a GET request. It should be a POST request.

$.ajax({
            type: "post",

You'll also need to post your most recent code so I can see the changes.

Edris899's avatar

No.I think no token in the html?

The javascript.

<script type="text/javascript">
     $("#myform").on("submit", function(e) {
            e.preventDefault(); // prevent the form submission
            console.log("benaan");
            
            $.ajax({
                type: "post",
                dataType: 'JSON',
                url: '/users/photos/movePhotosToAlbumAjax/',
                data: $('#myform').serialize(), // serialize all form inputs
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
                success: function(response) {
                    console.log("de response terug");
                    console.log(response);
                },
                error: function(data) {
                    console.log(data)
                }
            });
        });
</script>
Cronix's avatar

That should be covered if you have

<meta name="csrf-token" content="{{ csrf_token() }}">

in the <head> of your template. But I don't think that would trigger the error you mentioned. The error shows you making a get request. The route method is post.

Edris899's avatar

Yes I do indeed have that in the html<head> Hmm yeah thats so weird haha :P Running on ubuntu apache2

Edris899's avatar

The route is already post.

    Route::post('users/photos/movePhotosToAlbumAjax/','AlbumsController@movePhotosToAlbumAjax')->name('users.photos.movePhotosToAlbumAjax');
Edris899's avatar

I changed

url: '/users/photos/movePhotosToAlbumAjax/',

To this

url: '/users/photos/movePhotosToAlbumAjax',

In the controller I used this.

public function movePhotosToAlbumAjax(Request $request){
        $request->photo_id; // array of all selected photo id's
        $album_id = $request->album_id; // id of album
        
        return ['success' => true,'album_id' => $album_id];
    }

Getting the following results in the console after clicking on submit.

{success: true, album_id: "52"}

So I thinks it works?

Edris899's avatar

Getting also data with the photo_id

{success: true, album_id: "52", photo_id: Array(2)}
album_id
:
"52"
photo_id
:
(2) ["32", "33"]
success
:
true

So I think @Cronix it works? :D

Please or to participate in this conversation.