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

YusufGokcimen's avatar

[Solved] JSON Data Displayed on Screen Instead of Being Handled

After the user logs in, I trigger the updateCart function, but I'm unable to capture the returned JSON response. As a result, the JSON data is being printed to a black screen. I’ve provided the code below to explain the issue more clearly.

public function getcart() { $client = new Client();

$authenticationKey = Session::get('authenticationKey');

try {
    $response = $client->get('...', [
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'Authorization' => $authenticationKey
        ],
    ]);

    $cartData = json_decode($response->getBody()->getContents(), true);

    $currency = Session::get('currency');
    foreach ($cartData['data'] as &$product) {
        $product['currency'] = $currency;
    }

    return $cartData;

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}

}

Response from /getcart endpoint:

{ "data": [ { "id": 12345, "productId": 6789, "code": "ABC1234", "barcode": "9876543210123", "title": "Example Product 1 - Super Fast Charging Cable 5A 2M-Black", "brand": "BRANDX", "quantity": 3, "price": 15, "currency": "€", "image": "https://example.com/products/12345.jpg" }, { "id": 12346, "productId": 7890, "code": "XYZ5678", "title": "Example Product 2 - Leather Phone Case for iPhone 12 Pro Max", "brand": "CASEWORLD", "quantity": 5, "price": 30, "currency": "£", "image": "https://example.com/products/12346.jpg" } ], "success": true, "message": "Operation successful." }

JavaScript Code to Call getCart and Update Cart:

$(document).ready(function() { if ($('.cartcount').length > 0) { updateCart(); initializeCartButtons(); } });

function updateCart() { $.ajax({ url: getCartUrl, type: 'GET', success: function(data) {

        const $cartDropdown = $('#cart');
        $cartDropdown.empty();

        if (data.success) {
            $('.cartcount').text(data['data'].length);

            if (data['data'].length === 0) {
                $cartDropdown.append('<span class="empty">No products found.</span>');
            } else {
                const $cartList = $('<ul></ul>');
                let totalPrice = 0;
                let currency = data.currency; // Use the currency from response

                $.each(data['data'], function(index, item) {
                    const $cartItem = $('<li></li>');
                    let itemImageSrc = item.image ? item.image : '../assets/imgs/theme/default_image.png'; 
                    const $itemImage = $('<div class="shopping-cart-img"></div>').append(
                        $('<a></a>').attr('href', '../product/'+item.slug).append(
                            $('<img>').attr('src', itemImageSrc).attr('alt', item.title)
                        )
                    );
                    const $itemDetails = $('<div class="shopping-cart-title"></div>').append(
                        $('<h4></h4>').append(
                            $('<a></a>').attr('href', '../product/'+item.slug).text(item.title)
                        ),
                        $('<h4></h4>').append(
                            $('<span></span>').text(`${item.quantity} × `),
                            `${item.currency}${item.price}`
                        )
                    );
                    const $itemDelete = $('<div class="shopping-cart-delete"></div>').append(
                        $('<a class="text-body cdelcart-btn"></a>').attr('data-id', item.productId).append(
                            $('<i class="fi-rs-cross-small"></i>')
                        )
                    );

                    // totalPrice calculation (not added to cart list yet)
                    totalPrice += item.salePrice * item.quantity;
                });

                const $cartFooter = $('<div class="shopping-cart-footer"></div>');
                const $totalPrice = $('<div class="shopping-cart-total"></div>').append(
                    $('<h4></h4>').text(`Total: `).append(
                        $('<span></span>').text(`${currency} ${totalPrice.toFixed(2)}`)
                    )
                );
                const $cartButtons = $('<div class="shopping-cart-button"></div>').append(
                    $('<a></a>').attr('href', '../cart').text('My Cart')
                );

                $cartFooter.append($totalPrice, $cartButtons);
                $cartDropdown.append($cartList, $cartFooter);

                const token = $('meta[name="csrf-token"]').attr('content');

                $('.cdelcart-btn').on('click', function() {
                    const productId = $(this).data('id');
                    handleCartAction('/delcart', productId, token, 'Product Removed from Cart!', 'Product has been successfully removed from your cart.');
                });

            }
        } else {
            $cartDropdown.append('<span class="error">An error occurred while fetching cart data.</span>');
        }
    },
    error: function() {
        console.error('Error:', error);
        const $cartDropdown = $('#cart');
        $cartDropdown.empty();
        $cartDropdown.append('<span class="error">An error occurred while fetching cart data.</span>');
    }
});

}

Problem Explanation:

After the user logs in, I call the updateCart function. The function performs an AJAX request to the getCart URL and expects a JSON response. However, the JSON response is not properly handled, and instead, it is being printed directly to the screen as raw JSON data. I am unable to capture or process the response in the success callback of the AJAX request.

0 likes
4 replies
YusufGokcimen's avatar

@s4muel I tried this but it didn't work and yes getCart() method returns json from /getcart

YusufGokcimen's avatar

@s4muel public function login(Request $request) { $email = $request->input('username'); $password = $request->input('password');

$client = new Client();

try {
    $response = $client->post('......', [
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ],
        'body' => json_encode([
            'username' => $email,
            'password' => $password
        ]),
    ]);

    $userData = json_decode($response->getBody()->getContents(), true);

    session([
        'authenticationKey' => $userData['data']['authenticationKey']
    ]);
    session(['currency' => $userData['data']['visibleCurrencyUnit']]);

    return response()->json(['error' => False, 'message' => 'Hoş geldiniz ' . $userData['data']['name'] . ' ' . $userData['data']['surname']]);
} catch (\Exception $e) {
    return response()->json(['error' => True, 'message' => $e->getMessage()], 400);
}

}

Actually, I have this problem after the user logs in, the user logs in and sees the json data on the screen, if he refreshes the page, everything works fine, but I do not want to see this json data on the screen after logging in.

YusufGokcimen's avatar

[SOLVED] I now check whether the user is logged in using middleware and return a boolean value. Based on this value, I call the updateCart function.

Thank you for your answers

Please or to participate in this conversation.