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

Laracast13's avatar

Laravel get json response using ajax

Hello

Sending ajax request which give total price.

In controller (this works in $total gives number value)


    public function getCalculate($a_id,$b_id)
    {        
        $priceA = PriceA::select('price')->where('id',$a_id)->first(['price'])->price;
        $priceB = PriceB::select('price')->where('id',$b_id)->first(['price'])->price;
        $total = $priceA + $priceB;
        return response()->json($total); 
    }

blade file using this ajax , but can not get data


        $('#selectbox').on('change', function(){ 
            if(b_id) {
                $.ajax({
                    url: "{{  url('/get/calculate/') }}/"+a_id+"/"+b_id,
                    type:"POST",
                    dataType:"json",
                    success:function(data) {
                      if(data){
                        $("#totalPrice").empty();
                       
                $("#totalPrice").append(value.price);   // how get data  here ?
                                 
                           console.log(data);      
                      }else{ $("#totalPrice").empty();} 
                    },
                });
            } else {$("#totalPrice").empty();}
        });

0 likes
2 replies
MichalOravec's avatar
Level 75

In controller

return response()->json(['price' => $total]);

In js

$("#totalPrice").text(data.price);

By the way queries in the controller could be

$priceA = PriceA::findOrFail($a_id)->price;

$priceB = PriceB:::findOrFail($b_id)->price;
1 like
tykus's avatar

First:

$priceA = PriceA::where('id', $a_id)->value('price');
$priceB = PriceB::where('id',$b_id)->value('price');

return response()->json(['total' => $priceA + $priceB]);

Then, depending on the #totalPrice element, you will either append() or text(), or value():

$.ajax({
  url: "{{  url('/get/calculate/') }}/"+a_id+"/"+b_id,
  type:"POST",
  dataType:"json",
  success:function(data) {
    if(data){
      $("#totalPrice").empty();
      $("#totalPrice").append(data.total);
    }else{
      $("#totalPrice").empty();
    } 
  }),
1 like

Please or to participate in this conversation.