1
votes

I'm building a Laravel app with jQuery. I've a form with a select box(list of products) and text input fields.

My requirement is when I choose a product from the Select box at the top, the value of all other fields should update according to the products value that is fetched from database for the selected product.

This is my js script:

$(document).ready(function() {

    var divKey = $( "#proposed_product option:selected" ).val();

    $( "#proposed_product" ).change(function() {
        updateKeyValues();
    });

    function updateKeyValues() {
        $("#proposed_product").val(divKey);
        console.log(proposed_product); //what to do here..???

    }

});

My laravel function to return gigs list:

public function proposegigs($id){
    $gig = Gig::findOrFail($id);
    return $gig;

Can somebody help how to achieve this?

2
make some ajax call otherwise client side js can't figure out what to do with server side data - devsourav
The requirement is to fetch the selected product's details like title, description, price etc. from the database and fill other fields with those data. - chuck

2 Answers

1
votes

Make an ajax call to get the data

$( "#proposed_product" ).change(function() {
    $.ajaxSetup({
       headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
       url: "{{ route('your-route') }}",
       type: "POST",
       data: {id: $( "#proposed_product :selected" ).val()}, //send data to controller
       success: function(result){
           console.log(result);
           //check the console then put the data where you want
       }
    });

    $.ajax();
});

In your controller return json response

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json(['data' => $gig]);
}
1
votes

you can disable unchanged items like following,

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

    var selectedItem = $(this)

    $.each( $( "#proposed_product" ).children('option'), function (index, item) { 
        if(selectedItem.val() != $(item).val()) {
            $(this).prop('disabled', true)
        }
    })
});

Also, you can change option items by data which result of request you send.

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

    var selectedItem = $(this)

    // Example Request
    $.get('https://httpbin.org/get', function(data) {
        $.each( $( "#proposed_product" ).children('option'), function (index, item) { 
            if(selectedItem.val() != $(item).val()) {
                $(this).text(data.origin)
            }
        })
    })
});

Also, your response must be json format,

public function proposegigs(Request $request){
    $gig = Gig::findOrFail($request->id);
    return response()->json($gig, 200);
}