Search code examples
javascriptjqueryhtmlmodel-view-controllerlaravel-5.5

Store data of JSON response into multiple variables


I have been obtaining the json response the same as i needed, but it is in data response. i want to store it in different variables so that i can use it in javascript the way i need to.

function which is passing the json data is:

 public function get_Ajax(Request $request)
    {
        $b_id = $request->input('b_id');

            $pays = Booking::find($b_id);
            foreach ($pays->payments as $pay) {
                $paymentss[] = $pay->payment;
                $p_dates[] = $pay->created_at->format('d-M-Y');
            }

        return response()->json([
            $paymentss,
            $p_dates
        ]);
    }

Button which is calling the function is:

<button class="btn btn-block btn-primary " data-toggle="modal" data-href="#full-width" href="#full-width" onclick="showdetail({{$book->id}})" style="background-color: #224777">View Payments Schedule</button>

and the function which is obtaining the response

function showdetail(b_id) {
$.get('/my-account/get_payments?b_id='+b_id, function(data){
alert(data)
});
}

kindly let me know how i can split the data into the two variables.


Solution

  • When you say "use it in the way I need to" what exactly do you mean? Are you altering the data? If not then you can just pass the JSON object around however you want and it'll be fine, no need to do anything more than

    function showdetail(b_id) {
      $.get('/my-account/get_payments?b_id='+b_id, function(data){
        let var1 = data,
            var2 = data;
      });
    }
    

    If you're going to be editing the data in different ways the easiest way to copy JSON is just to stringify and then parse it like so

    function showdetail(b_id) {
      $.get('/my-account/get_payments?b_id='+b_id, function(data){
        let var1 = JSON.parse(JSON.stringify(data)),
            var2 = JSON.parse(JSON.stringify(data));
      });
    }