0

I am trying to create 2 dependent select boxes in my Laravel project, so that when I select a choice on the first select box, the contents of the second select box will be generated from the database based on this option, i tried to use ajax for this task it almost worked the problem is that i can't get to translate the data returned from my controller hense i can't fill out the second select box here is my controller :

public function get_fournisseurs($id){

    $fou= DB::table('four_cat')
        ->join('fournisseurs','four_cat.four', '=', 'fournisseurs.id')
        ->where('four_cat.cat','=', $id)
        ->select('fournisseurs.id','fournisseurs.nomSociete','fournisseurs.id','fournisseurs.tel')
        ->get();
    return json_encode(array('data'=>$fou));

 }

And here is the ajax methode that is trying to get the result from controller and fill up the second select box according to that result :

<script>
    $fou=null;
    $("#first-choice").change(function() {
        var cat = $("#first-choice").val();
        //console.log(cat);
        $.ajax({
            url: "{{ url('get_fournisseurs') }}"+'/'+cat ,
            method:'GET',
            dataType: 'json',
            success: function(dataResult){
                var resultData = dataResult.data;
                console.log(resultData);

                $.each(resultData,function(i,row){
                    //$('#second-choice').append('<option value="' +  row.id + '" title="Mobile :'+ row.tel +'">' +  row.id- row.nomSociete + '</option>');
                    $('#second-choice').append(new Option(row.id- row.nomSociete ,row.id ));
                })

            }
        });
    });


</script>

so this keeps giving me Nan instead of the actual data returned from the controller

Errors of Console

so can someone tell me what's wrong with my code ? (My form is correct that's why i didn't show the code to avoid to much code )

youss
  • 57
  • 8
  • `parseInt(row.id)- toString(row.nomSociete)` looks like you're subtracting a string from a number? –  Sep 01 '21 at 17:57
  • no its just for better display like this example : 1- A G M I (id- company's name) – youss Sep 01 '21 at 18:00
  • ill remove the parseInt to avoid confusion so people would focus on my recent code giving me Nan – youss Sep 01 '21 at 18:03
  • That's not how string composition works though; your code is trying to subtract a string from a number, resulting in `NaN`. To compose a string you add the individual strings together (`row.id + "- " + row.nomSociete`) or use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). –  Sep 01 '21 at 19:54
  • Duplicate: [How to insert variables in JavaScript strings?](https://stackoverflow.com/questions/19105009/how-to-insert-variables-in-javascript-strings) –  Sep 01 '21 at 19:56

0 Answers0