简体   繁体   中英

Uncaught TypeError: Cannot read property '' of undefined using Laravel and AJAX

I have the following select box:

 <select class="form-control select2-single" data-width="100%" name="numero_projet" id="numero_projet">
    <option label="&nbsp;">&nbsp;</option>
    @foreach($projets as $projet)
      <option data-id="{{$projet->id_projet}}" value="{{$projet->id_projet}}">{{$projet->numero_projet}}</option>
    @endforeach
   </select>

And the following ajax code to get data :

<script>
    $(document).ready(function(){


        $('#numero_projet').change(function(){

            var id_projet = $(this).find("option:selected").data("id");

            console.log(id_projet);

        $.ajaxSetup({

            headers: { 'X-CSRF-TOKEN': 
        $('meta[name="_token"]').attr('content') }

          });
        
        $.ajax({
                  
            url:"getProjet/"+id_projet,
            type:"GET",
             success:function(html){

            var content = html.content;
   
        $("div.name_casting").append(content.id_casting);
    
        }
            
    })
        })

        })
</script>

And the following controller:

 public function getProjet()

    {

    if(request()->ajax())
        {
           $id_projet = request('numero_projet');

          $projets_casting = Projet_Casting::where('id_projet',$id_projet)->get();

            return response()->json(['projets_casting' => $projets_casting]);
          
        }
    }

And I have the following view where I should display the data that I get from controller:

 <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Select from Library</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @foreach($projets_casting as $projet_casting)
                    <div class="modal-body scroll pt-0 pb-0 mt-4 mb-4">
                        <div class="accordion" id="accordion">
                            <div class="mb-2">
                                <button class="btn btn-link p-0 folder-button-collapse" data-toggle="collapse"
                                    data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                    <span class="icon-container">
                                        <i class="simple-icon-arrow-down"></i>
                                    </span>
                                    <span class="folder-name">Castings</span>
                                </button>
                                <div id="collapseOne" class="collapse show" data-parent="#accordion">
                                    <div class="list disable-text-selection">
                                        <div class="row">
                                       
                                            <div class="col-6 mb-1 sfl-item-container casting"
                                                data-preview-path="img/products/chocolate-cake-thumb.jpg"
                                                data-path="img/products/chocolate-cake-thumb.jpg"
                                                data-label="chocolate-cake-thumb.jpg">
                                                <div class="card d-flex mb-2 p-0 media-thumb-container">
                                                    <div class="d-flex align-self-stretch">
                                                        <img src="img/products/chocolate-cake-thumb.jpg" alt="uploaded image"
                                                            class="list-media-thumbnail responsive border-0" />
                                                    </div>
                                                    <div class="d-flex flex-grow-1 min-width-zero">
                                                        <div
                                                            class="card-body pr-1 pt-2 pb-2 align-self-center d-flex min-width-zero">
                                                            <div class="w-100">
                                                                <p class="truncate mb-0">{{$projet_casting->id_casting}}</p>
                                                            </div>
                                                        </div>
                                                        <div
                                                            class="custom-control custom-checkbox pl-1 pr-1 align-self-center">
                                                            <label class="custom-control custom-checkbox mb-0">
                                                                <input type="checkbox" class="custom-control-input">
                                                                <span class="custom-control-label"></span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                         

                                            
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                 @endforeach    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" data-dismiss="modal">Annuler</button>
                        <button type="button" class="btn btn-primary sfl-submit">Selectionner</button>
                    </div>
                </div>
            </div>

It should display in this div the id_casting of each projects

<div class="w-100 name_casting">
 <p class="truncate mb-0">ok</p>
</div>

But I get the following error:

Uncaught TypeError: Cannot read property 'id_casting' of undefined

What is wrong with my code?

Update

I have the following HTML in my view:

 <div id="collapseOne" class="collapse show" data-parent="#accordion">
                                    <div class="list disable-text-selection">
                                        <div class="row">
                                       
                                            <div class="col-6 mb-1 sfl-item-container casting"
                                                data-preview-path="img/products/chocolate-cake-thumb.jpg"
                                                data-path="img/products/chocolate-cake-thumb.jpg"
                                                data-label="chocolate-cake-thumb.jpg">
                                                <div class="card d-flex mb-2 p-0 media-thumb-container casting2">
                                                    <div class="d-flex align-self-stretch">
                                                        <img src="img/products/chocolate-cake-thumb.jpg" alt="uploaded image"
                                                            class="list-media-thumbnail responsive border-0" />
                                                    </div>
                                                    <div class="d-flex flex-grow-1 min-width-zero">
                                                        <div
                                                            class="card-body pr-1 pt-2 pb-2 align-self-center d-flex min-width-zero">
                                                            <div class="w-100 castings">
                                                                <p class="truncate mb-0">OK</p>
                                                            </div>
                                                        </div>
                                                        <div
                                                            class="custom-control custom-checkbox pl-1 pr-1 align-self-center">
                                                            <label class="custom-control custom-checkbox mb-0">
                                                                <input type="checkbox" class="custom-control-input">
                                                                <span class="custom-control-label"></span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                         

                                            
                                        </div>
                                    </div>
                                </div>

And I'm trying the following script:

<script>
    $(document).ready(function(){


        $('#numero_projet').change(function(){

            var id_projet = $(this).find("option:selected").data("id");

            console.log(id_projet);

        $.ajaxSetup({

            headers: { 'X-CSRF-TOKEN': 
        $('meta[name="_token"]').attr('content') }

          });
        
        $.ajax({
                  
            url:"getProjet/"+id_projet,
            type:"GET",
             dataType:"json",
             success:function(json){
                     renderTemplate(json)
             }
    });

        function renderTemplate(json) {
        var content = ` <div">
                   <p class="truncate mb-0">${json.id_casting}</p>
                    </div>`;

    $("div.name_casting").append(content);
}
        })

        })

</script>

But I have nothing. I have always OK and I have no error!

UPDATE2

Now I can get the data that I want, but I get multiple rows in the same time so I should having multiple divs in my HTML.

I'm getting the following result:

在此处输入图片说明

While I shoult get the 18 in a div and 19 in other div and not in the same place.

Analogous to @professor 's answer :

  1. Use the JSON (recommended)
    The Controller doesn't have to be modified
    In your blade/JavaScript, change the following:
$.ajax({                  
    url:"getProjet/"+id_projet,
    type:"GET",
    dataType:"json",
    success:function(json){
        renderTemplate(json)
    }        
});

function renderTemplate(json) {
    var content = `<div>
        ${json.castings.map((casting) => casting.id_projet)}
    </div>`;

    $("div.name_casting").append(content);
}
  1. Use the HTML
    The blade view and JavaScript
    In your controller, change the following:
public function getProjet()
{
    if(request()->ajax())
    {
        $id_projet = request('numero_projet');

        $projets_casting = Projet_Casting::where('id_projet',$id_projet)->get();

        return view('your-view', ['projets_casting' => $projets_casting]);          
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM