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

Rumnaz khan's avatar

Displaying Json response

hi! In my application there is a user select field. when a user is selected it should show the users info like their total purchase sales and balance. so far i've done this:

this is the blade file

<td>
<select class="form-control select2 {{ $errors->has('team') ? 'is-invalid' : '' }}" name="fabricator_id" id="fabricator_id">
@foreach($fabricators as $user)
            <option value="{{ $user->id }}" >{{ $user->identity }}</option>
 @endforeach
 </select>
</td>
<tr id="user_info">
                            <td>
                                Total Purchase: <div id="someDiv">this is where i want my data</div>
                            </td>
                            <td>
                                Total Points:
                            </td>
                            <td>
                                Total Redeemed Points:
                            </td>
                            <td>
                                Total Available Points:
                            </td>

                        </tr>

<script type="text/javascript">
    $("#user_info").hide();

    $(document).ready(function () {
        //on change type
        $('#fabricator_id').change(function (e) {

            $.ajax({
                url: "<?= url('/admin/fabricator/') ?>/" + $(this).val(),
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                   $("#user_info").show();
                    alert(data.name);
                }
            });
        });

    });
</script>

Controller:

    public function fabricator($id){
        $fabricator_details = User::select(\DB::raw('users.*, SUM(transactions.stock) as total_purchase, SUM(transactions.reward_points) as total_points, SUM( (transactions.redeem) )as redeemed_points' ))
         ->where('users.id', '=', $id)
         ->leftJoin('transactions', 'transactions.fabricator_id', '=', 'users.id')
         ->get();

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

and this is my json response:

{"data":[{"id":20,"identity":"68099","name":"Md. Shahidul Islam","email":"[email protected]","email_verified_at":null,"created_at":"2021-12-30 05:06:34","updated_at":"2022-03-07 09:49:17","deleted_at":null,"team_id":16,"image":"","balance":1591140,"division":"Keraniganj","district":"Dhaka","upazilla":"Dhaka","total_purchase":"8008700","total_points":"1601740","redeemed_points":"12600"}]}

alert(data.name) alerts undefined

0 likes
8 replies
s4muel's avatar

data is an array in that json response, try with this first

alert(data[0].name);

and then you can manipulate the response in controller, so it returns the data as an object (instead of array of objects) probably like this:

$fabricator_details = User::select(\DB::raw('users.*, SUM(transactions.stock) as total_purchase, SUM(transactions.reward_points) as total_points, SUM( (transactions.redeem) )as redeemed_points' ))
         ->where('users.id', '=', $id)
         ->leftJoin('transactions', 'transactions.fabricator_id', '=', 'users.id')
         ->get()
         ->first();
s4muel's avatar

@Rumnaz khan ehm, is it alert(data.data[0].name); then?

anyway, see my updated post, and add the ->first() method to return single User instead of collection

s4muel's avatar

@Rumnaz khan in that case, the response is not received OK, or in a structure, you mention.

here you can see a dirty working example: https://phpsandbox.io/e/x/7gxn0?&layout=EditorPreview&iframeId=ezhfve9173&theme=dark&defaultPath=/&showExplorer=no&openedFiles=/resources/views/welcome.blade.php,/routes/web.php

i get that the alert call is just for testing purposes. just try to use browser debugging window. where you can debug the variables and see the structure of the response.

my suggestions:

  • add that ->first() to the controller, so single item is returned instead of collection
  • do not add the data key in your response, i think this makes you confused
public function fabricator($id){
        $fabricator_details = User::select(\DB::raw('users.*, SUM(transactions.stock) as total_purchase, SUM(transactions.reward_points) as total_points, SUM( (transactions.redeem) )as redeemed_points' ))
         ->where('users.id', '=', $id)
         ->leftJoin('transactions', 'transactions.fabricator_id', '=', 'users.id')
         ->get()
         ->first();

        return response()->json($fabricator_details);
    }
  • use moustache to print variables in blade instead of <?= (optional)
  • rename the data (in success callback), so you clearly know what is what
  • use console log to investigate the response + browser dev tools (usually F12 in browser)
$.ajax({
    //btw: isn't the slash in the middle of the url duplicated?
    url: "{{ url('/admin/fabricator/') }}/" + $(this).val(),
    method: 'GET',
    dataType: 'json',
    success: function (response) {
        console.log(response);
        //alert(response.name);
        //todo: assign return values to you html elements, so the user_info box is updated with received values
        //response.name, response.total_points, response.redeemed_points ...

        $("#user_info").show();
    }
});
tykus's avatar

@Rumnaz khan do you really want a native browser alert to display the data, or do you intend to render the result into the view?

tykus's avatar

@Rumnaz khan then I suggest the fabricator action returns a partial view - where you can organise the data into a HTML structure as normal. The only difference is you return the render method -

public function fabricator($id)
{
    $fabricator_details = User::select(\DB::raw('users.*, SUM(transactions.stock) as total_purchase, SUM(transactions.reward_points) as total_points, SUM( (transactions.redeem) )as redeemed_points' ))
         ->where('users.id', '=', $id)
         ->leftJoin('transactions', 'transactions.fabricator_id', '=', 'users.id')
         ->first();

    return view('partials.your-partial', compact('fabricator_details'))->render();
}

Then, in the success callback you can append the HTML received from the response

Please or to participate in this conversation.