php ajax how to display output?

Can you please tell me what is wrong with this code? It’s not giving me any output after clicking submit.

$('#btnRun').click(function() {
  $.ajax({
    url: "libs/php/getCountryCode.php",
    type: 'POST',
    dataType: 'json',
    data: {
      lat: $('#lat1').val(),
      lng: $('#long1').val()
    },
    success: function(result) {
      console.log(JSON.stringify(result));

      if (result.status.name == "ok") {
        $('try').html(result.data.countryCode);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      // your error code
    }
  });
});

The result is obtained is this format:

{
  "languages": "de-AT,hr,hu,sl",
  "distance": "0",
  "countryCode": "AT",
  "countryName": "Austria"
}

recurring payment Global payment

I have a php code for a recurring payment to GP, but the payment gateway ends on error 31.

I was told by support that the signature is 2x base64 encoded and therefore you are getting a signature error.

In the code, focus on this line:
$params[‘regularSubscriptionPaymentRequest’][‘signature’] = new SoapVar($params[‘regularSubscriptionPaymentRequest’][‘signature’], XSD_BASE64BINARY);

Current code

<?php

$wsdl = __DIR__ . '/cws_v1.wsdl';
$privateKey = __DIR__ . '/private-key.pem';
$publicCert = __DIR__ . '/pub-key.pem';
$privateKeyPassword = '**************';

$soapLocation = 'https://test.3dsecure.gpwebpay.com/pay-ws/v1/PaymentService';

function signMessage($data, $privateKeyPath, $password)
{
    $privateKey = openssl_pkey_get_private("file://{$privateKeyPath}", $password);
    if (!$privateKey) {
        throw new Exception('error private key');
    }

    if (!openssl_sign($data, $signature, $privateKey)) {
        throw new Exception('error signature');
    }

    return base64_encode($signature);
}


function processRegularSubscriptionPayment($merchantNumber, $privateKeyPath, $password, $wsdl, $soapLocation)
{
    try {
        $streamContext = stream_context_create(array(
            'http' => array(
                'header' => 'Content-Type: application/soap+xml; charset=utf-8',
            )
        ));


        $client = new SoapClient($wsdl, array(
            'trace' => 1,
            'exceptions' => true,
            'location' => $soapLocation,
            'soap_version' => SOAP_1_1, 
            'encoding' => 'UTF-8',
            'cache_wsdl' => WSDL_CACHE_NONE,
            'stream_context' => $streamContext,

        ));

        $messageId = date('YmdHis') . rand(1000, 9999);

        $params = [
            'regularSubscriptionPaymentRequest' => [
                'messageId' => $messageId,
                'provider' => 'XXXX',
                'merchantNumber' => $merchantNumber,
                'paymentNumber' => '123456789',
                'masterPaymentNumber' => '123456788',
                'orderNumber' => '123456789',
                'captureFlag' => 1, 
                'cardHolderData' => [
                    'cardholderDetails' => [
                        'name' => 'Name Surname',
                        'email' => '[email protected]'
                    ],
                ],
            ]
        ];
        $name = htmlspecialchars($params['regularSubscriptionPaymentRequest']['cardHolderData']['cardholderDetails']['name'], ENT_QUOTES, 'UTF-8');

        $email = htmlspecialchars($params['regularSubscriptionPaymentRequest']['cardHolderData']['cardholderDetails']['email'], ENT_QUOTES, 'UTF-8');


        $params['regularSubscriptionPaymentRequest']['cardHolderData']['cardholderDetails']['name'] = $name;

        $params['regularSubscriptionPaymentRequest']['cardHolderData']['cardholderDetails']['email'] = $email;

        $dataToSign = $params['regularSubscriptionPaymentRequest']['messageId']
            . "|" . $params['regularSubscriptionPaymentRequest']['provider']
            . "|" . $params['regularSubscriptionPaymentRequest']['merchantNumber']
            . "|" . $params['regularSubscriptionPaymentRequest']['paymentNumber']
            . "|" . $params['regularSubscriptionPaymentRequest']['masterPaymentNumber']
            . "|" . $params['regularSubscriptionPaymentRequest']['orderNumber']
            . "|" . $params['regularSubscriptionPaymentRequest']['captureFlag']
            . "|" . $params['regularSubscriptionPaymentRequest']['cardHolderData']['cardholderDetails']['name']
            . "|" . $params['regularSubscriptionPaymentRequest']['cardHolderData']['cardholderDetails']['email'];


        $params['regularSubscriptionPaymentRequest']['signature'] = signMessage($dataToSign, $privateKeyPath, $password);

        $params['regularSubscriptionPaymentRequest']['signature'] = new SoapVar($params['regularSubscriptionPaymentRequest']['signature'], XSD_BASE64BINARY);

        $response = $client->__soapCall('processRegularSubscriptionPayment', [$params]);

        if (isset($response->resultCode) && $response->resultCode == '0') {
            return  $response->resultMessage;
        } else {
            return  $response->resultCode . ' - ' . $response->resultMessage;
        }
    } catch (SoapFault $e) {
        print_r($e);
        return "SOAP error: " . $e->getMessage();
    } catch (Exception $e) {
        return "error: " . $e->getMessage();
    }
}


$merchantNumber = '147258369';
echo processRegularSubscriptionPayment($merchantNumber, $privateKey, $privateKeyPassword, $wsdl, $soapLocation);

compare and merge two array of objects

Here are two arrays which the first array is the main one and I need to update the value of every object that exist is the second array recursively by comparing their names.

Actually the first array is my form schema that might change occasionally And the second on is user filled data (schema + values). As user can update their filled forms, I need to show the new schema along with filled values of each object.

Main Array:

[
  {
    name: '6tb76sc'
  },
  {
    name: 'df45hf'
  },
  {
    name: 'ctb360f',
    childs: [
      {
        name: 'h83gus'
        childs: [
         {
           name: 'u8yh49'
         }
        ]
      }
    ]
  },
  {
    name: 'i6g7bau'
  }
]

Second Array:

[
  {
    name: '6tb76sc',
    value: 'test'
  },
  {
    name: 'ctb360f',
    childs: [
      {
        name: 'h83gus',
        value: 'test1'
        childs: [
         {
           name: 'u8yh49',
           value: 'test2'
         }
        ]
      }
    ]
  },
]

Needed output:

[
  {
    name: '6tb76sc',
    value: 'test'
  },
  {
    name: 'df45hf'
  }
  {
    name: 'ctb360f',
    childs: [
      {
        name: 'h83gus',
        value: 'test1'
        childs: [
         {
           name: 'u8yh49',
           value: 'test2'
         }
        ]
      }
    ]
  },
  {
    name: 'i6g7bau'
  }
]

Why does a fresh install of phpactor using neovim give me the following lsp error?

I’m on Windows using Neovim, and I use Mason to install all my LSPs (in this case phpactor). Below is a snippet of my setup function and the LSP Log error I’m receiving.

I can’t even try to get any further because of the error. As soon as the buffer opens, it exits with an error. I’m trying to see if I can get it to work for php and blade files as a side note. What you see below is all I have done for phpactor and nothing else so far.

lsp.lua

  ["phpactor"] = function()
      lspconfig.phpactor.setup {
          filetypes = { "php", "php_only", "blade" },
          root_dir = vim.fs.root(0, { "composer.json", ".git", "phpactor.json", "phpactor.yml" }),
          cmd = { "phpactor", "language-server" },
          init_options = {
              ["indexer.supported_extensions"] = { "blade" },
              ["language_server_completion.trim_leading_dollar"] = true,
              ["language_server_phpstan.enabled"] = false,
              ["language_server_psalm.enabled"] = false,
          }
      }
  end,

LSP Log

[ERROR][2024-10-27 15:40:28] .../vim/lsp/rpc.lua:770 "rpc" "...\AppData\Local\nvim-data\mason\bin\phpactor.CMD" "stderr" "PHP Fatal error: Uncaught TypeError: trim(): Argument #1 ($string) must be of type string, false given in phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php:60nStack trace:n#0 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php(60): trim(false)n#1 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php(31): HumbugBox436\KevinGH\RequirementChecker\Terminal::initDimensions()n#2 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Printer.php(28): HumbugBox436\KevinGH\RequirementChecker\Terminal->getWidth()n#3 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Checker.php(17): HumbugBox436\KevinGH\RequirementChecker\Printer->__construct(32, false)n#4 phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/bin/check-requirements.php(22): HumbugBox436\KevinGH\RequirementChecker\Checker::checkRequirements()n#5 C:\Users\thadl\AppData\Local\nvim-data\mason\packages\phpactor\phpactor.phar(13): require('phar://C:/Users...')n#6 {main}n thrown in phar://.../AppData/Local/nvim-data/mason/packages/phpactor/phpactor.phar/.box/src/Terminal.php on line 60n"

When I tried using Intelephense, the LSP works for PHP files but fails on blade files. It recognizes the blade file, attaches but doesn’t provide any LSP functionality. I decided to try phpactor but I’m also stuck there.

I’m a novice with neovim, and I’m doing my best with the configurations so it’s possible I’m missing something obvious or doing something wrong.

I essentially want a working PHP LSP for neovim where it works with both PHP files and within .blade.php files. I managed to get the treesitter parser working for blade which took awhile but now I actually need the LSP to work.

Any advice to help me out would be awesome. I’m not sure where to go from here. 🙂 If you need to see anything I haven’t posted, let me know.

laravel -> file_put_contents(/var/www/laravel/storage/framework/views/9f1dc9629406f3376fc417dd6985a806.php): Failed to open stream: Permission denied

docker-compose.yaml

version: "3.8"

services:
  nginx:
    image: "nginx:stable-alpine"
    ports:
      - "8000:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./src:/var/www/laravel
    depends_on:
      - php
      - mysql
  php:
    build:
      context: dockerfiles
      dockerfile: php.Dockerfile
    volumes:
      - ./src:/var/www/laravel
  mysql:
    image: mysql:8.0
    ports:
      - "3316:3306"
    env_file:
      - ./env/mysql.env
  composer:
    build:
      context: dockerfiles
      dockerfile: composer.Dockerfile
    volumes:
      - ./src:/var/www/laravel
  artisan:
    build:
      context: dockerfiles
      dockerfile: php.Dockerfile
    volumes:
      - ./src:/var/www/laravel
    entrypoint: ["php", "/var/www/laravel/artisan"]

php.Dockerfile

FROM php:8.2-fpm-alpine

WORKDIR /var/www/laravel

RUN docker-php-ext-install pdo pdo_mysql

nginx.conf

server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    root /var/www/laravel/public;
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ .php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Error

enter image description here

in the php.dockerfile file I tried to add a line to change access

FROM php:8.2-fpm-alpine

WORKDIR /var/www/laravel

RUN docker-php-ext-install pdo pdo_mysql

RUN chmod -R 777 /var/www/laravel/storage          /*    <------  new line   */

I also tried to change access to the storage folder through WSL

@DESKTOP-VIGTBDU:/src/storage$ sudo chmod -R 777 .

Mail sending failed: stream_socket_enable_crypto(): Peer certificate CN=`98-81-57-227.cprapid.com’ did not match expected CN=`smtp.gmail.com’

Title: “Laravel Email Configuration Not Working on AWS WHM cPanel Server”

Body: “I am using AWS WHM cPanel Shared hosting server to send emails in my Laravel application. Below is my .env configuration for SMTP using Gmail:

Copy code
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
[email protected]
MAIL_PASSWORD="my_password"
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="${APP_NAME}"
MAIL_DEBUG=true

I have tried the following steps with AWS tech support:

Verified that port 587 is open
Double-checked Gmail SMTP settings
Confirmed that MAIL_PASSWORD is correct
However, I still can’t send emails. Could someone suggest a solution?

Issue with Dynamic Input Fields in PHP and JavaScript for Updating Journal Entries [closed]

I am working on a web application that allows users to update journal entries retrieved from a MySQL database. The form for editing these entries includes both static inputs (retrieved from the database) and dynamic inputs (added by the user). However, when I attempt to add a new dynamic input row and submit the form, I receive an error message indicating that an error occurred while processing the data. Specifically, the error is:

“An error occurred while processing the data. Please try again.”

The dynamic inputs do not seem to be recognized when the form is submitted, which prevents the update from being successful.

Problem Breakdown:
Static vs. Dynamic Inputs:

The static inputs (fetched from the database) work correctly.
The dynamic inputs (added using JavaScript) do not get processed correctly, leading to missing values in the $_POST array.
Expected Behavior:

When I click the “Add Row” button, a new row should be appended to the table with fields for the user to fill in (debtor, creditor, description, etc.).
Upon form submission, all values from both static and dynamic inputs should be processed correctly.
Actual Behavior:

Only the values from the static inputs are recognized in the $_POST array.
Dynamic fields return empty values or are not sent at all, resulting in the error message mentioned above.

PHP and JavaScript Code:

$account = $antiXss->xss_clean($_POST["account"]); 
$debtor = $_POST["debtor"]; 
$creditor = $_POST["creditor"]; 
$description = $antiXss->xss_clean($_POST["description"]); 
$acc_serial = $antiXss->xss_clean($_POST["acc_serial"]);
$has_error = false;

foreach ($account as $index => $count) {
if (isset($account[$index]) && isset($debtor[$index]) && isset($creditor[$index]) && isset($description[$index]) && isset($acc_serial[$index])) {
    $s_account = htmlspecialchars(strip_tags($antiXss->xss_clean($account[$index])));
    $s_debtor = filter_var($debtor[$index], FILTER_SANITIZE_NUMBER_INT);
    $s_creditor = filter_var($creditor[$index], FILTER_SANITIZE_NUMBER_INT);
    $s_description = htmlspecialchars(strip_tags($antiXss->xss_clean($description[$index])));
    $s_acc_serial = htmlspecialchars(strip_tags($antiXss->xss_clean($acc_serial[$index])));

    if (empty($s_account) || $s_debtor == "" || $s_creditor == "" || empty($s_description) || empty($s_acc_serial)) {
        echo '<script> $(document).ready(function(){ toastr.error("Please fill in all fields"); }) </script>';
        $has_error = true;
        break;
    }
    if ($s_debtor == $s_creditor) {
        echo '<script> $(document).ready(function(){ toastr.error("Debtor and Creditor cannot be equal in the same row"); }) </script>';
        $has_error = true;
        break;
    }
} else {
    echo '<script> $(document).ready(function(){ toastr.error("An error occurred while processing the data. Please try again."); }) </script>';
    var_dump($_POST["account"], $_POST["debtor"], $_POST["creditor"], $_POST["description"], $_POST["acc_serial"]);
    $has_error = true;
    break;
}
}

**JavaScript for Dynamically Adding Rows:
**

$('#dynamicAddRemove').on('change', '.select_acount', function() {
$(this).closest('tr').find('.acc_serial').val($(this).val()); });
$('#dynamicAddRemove').on('change', '.select_acount', function() {
$(this).closest('tr').find('.mount').val($(this).find("option:selected").text());
});


$(document).ready(function() {
  $('.js-example-basic-single').select2();
});

var dataElement = document.getElementById('data');
var data = JSON.parse(dataElement.dataset.rows);
var product_dd = "";
product_dd += '<select class="form-control select_acount js-example-basic-single select2" name="account[]" required>';
product_dd += '<option value="">--choose account--</option>';
if (Array.isArray(data)) {
data.forEach(function(item) {
  product_dd += '<option value="' + item.acc_serial + '">' + item.acc_name + '</option>';
});
} else {
console.error("Error: Invalid data format");
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr>'+
  '<td class="td">'+product_dd+'</td>'+
  '<td class="td"><input type="text" name="debtor[]" class="form-control debtor" required></td>'+
  '<td class="td"><input type="text" name="creditor[]" class="form-control creditor" required></td>'+
  '<td><input type="text" name="description[]" class="form-control" required></td>'+
  '<td><input type="hidden" name="acc_serial[]" class="form-control acc_serial" required></td>'+
  '<td><button type="button" class="btn btn-danger remove-tr"><i class="fas fa-trash"></i></button></td>'+
  '</tr>');
$('.js-example-basic-single').select2();
});

HTML

<tr>
    <td>
        <select class="form-control select_acount js-example-basic-single select2" name="account[]" required>
            <option value="<?php echo $_acc_serial_token;?>"><?php echo $_account;?></option>
        </select>
    </td>
    <td>
        <input type="text" style="max-width: 94px;" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false" name="debtor[]" value="<?php echo $_debtor;?>" class="form-control debtor" required>
    </td>
    <td>
        <input type="text" style="max-width: 94px;" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false" name="creditor[]" value="<?php echo $_creditor; ?>" class="form-control creditor" required>
    </td>
    <td>
        <input type="text" name="description[]" value="<?php echo $_description; ?>" style="min-width: 205px;" class="form-control" required>
    </td>
    <td>
        <input name="acc_serial[]" class="form-control acc_serial" type="hidden" value="<?php echo $_acc_serial_token; ?>" required>
    </td>
    <td>
        <button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash"></i></button>
    </td>
</tr>
  • I used var_dump($_POST) to check the new inputs after clicking the “Add Row” button. The output showed that the dynamically added inputs weren’t passed in $_POST.
  • I ensured that input names included [] (like debtor[] and creditor[]) to gather them as array fields, but the issue persists.
  • I tried validating the values with JavaScript and PHP to make sure they’re correctly set when adding a new row.

Woo commerce cart is taxing shipping separately not of total order

Woo commerce cart is taxing shipping separately not of total order. Simply I am trying to add 10 percent tax to overall order and its returning the wrong results.

Example : 

item price : $12600
shipping price :$140.98
tax 10% : 1266.90
total Price : $14,007.88

Total Price should amount to $14,015.07 and tax should be
$1274.10.After many tests, the items are taxed
correctly but the shipping is getting tax i think by its self, not 
tax inclusively as total order

Ideally  example results expect:

item 1  : $10
Item 2  : $10 
shipping: $5

Than tax everything at 10%.

Any idea’s?

Tried all combinations within woo commerce setting in regards to shipping and taxes.
Current tax rate set at 10%.

How to Fetch All Users from AD LDAP in Laravel Without Timeout or Memory Issues?

I’m currently working on a Laravel 10 application that integrates with Active Directory (AD) using the AdLdap2 package and PHP’s LDAP functions (PHP 8). However, I’m facing challenges when trying to fetch all users (over 20,000) from the LDAP server.

Here are the two methods I’ve tried:
Method 1: Using AdLdap2 Package

private function handleAdLdapUsersEx($provider): void
{
    try {
        $pageSize = 200;

        if ($this->searchBase->filter) {
            $provider->where($this->searchBase->filter);
        }

        $pagedUsers = $provider->select('distinguishedname', 'givenname', 'name', 'objectguid', 'samaccountname', 'userprincipalname', 'mail')
            ->whereEnabled()
            ->limit($pageSize)
            ->paginate($pageSize, $this->currentPage);
        
        dump($pagedUsers->count());
        
        if ($pagedUsers->count() > 0) {
            collect($pagedUsers->getResults())->chunk(100)->each(function ($chunkedUsers) {
                $this->handleBulk($chunkedUsers);
                unset($chunkedUsers);
                gc_collect_cycles();
            });

            if ($pagedUsers->count() === $pageSize) {
                ImportUsersJob::dispatch($this->searchBase, $this->ldapConnector, $this->ldapConfig, $this->currentPage + 1);
            }
        }
    } catch (Exception $e) {
        dd($e->getMessage());
    }
}

In this method, I set a limit for pagination, even with limit and pagination I am getting all the records in one page, but I’m still experiencing timeouts. Setting public $timeout = 600; works, but I’d like to avoid hardcoding a timeout.

Method 2: Using PHP LDAP Functions

private function handleAdLdapUsers($provider, $ldapConnector): void
{
    try {
        $usersFetched = 0;
        $lastUserEntry = null;

        $ldapConnection = ldap_connect($provider->getConnection()->getHost());
        ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_bind($ldapConnection, $ldapConnector->getUsernames(), $ldapConnector->getPassword());

        $filter = !empty($this->searchBase->filter) ? $this->searchBase->filter : "(objectClass=*)";

        $result = @ldap_search($ldapConnection, $provider->getDn(), $filter, [], 0, 1);
        $firstEntry = ldap_first_entry($ldapConnection, $result);

        while ($firstEntry) {
            $attributes = ldap_get_attributes($ldapConnection, $firstEntry);

            $users = $provider->select('distinguishedname', 'givenname', 'name', 'objectguid', 'samaccountname', 'userprincipalname', 'mail', 'usncreated')
                ->whereEnabled()
                ->get($attributes);

            if ($users->count() > 0) {
                $this->handleBulk($users);
                $usersFetched = $users->count();
            } else {
                break;
            }

            $lastUserEntry = ldap_next_entry($ldapConnection, $firstEntry);
            $firstEntry = $lastUserEntry;
        }

        ldap_unbind($ldapConnection);
    } catch (Exception $e) {
        dd($e->getMessage());
    }
}

This method returns a “Sizelimit exceeded” warning and only fetches 1000 records. I suppressed the warning with @ldap_search, but I still need a way to fetch all users (potentially over 50,000) without hitting size limits or running into memory issues.

  1. How can I modify my queries or pagination to handle fetching all users efficiently?
  2. Are there best practices for dealing with large datasets in Laravel when querying LDAP?
  3. Is there a way to configure the LDAP server to allow fetching more than the default size limit?

Any help or guidance would be greatly appreciated!

How to use sqrt in gmp without loosing data?

I am working with big integer.

I have two equations:

  1. $n = m^4 = “66288484664777839292466735359294353535658376759494957”
  2. x = 4m – 11

To solve it I am using gmp_sqrt (two times)

   $m = gmp_sqrt(gmp_sqrt($n));

After that I am putting value of $m in equation 2. But it is not giving me the desired result because gmp_sqrt is ignoring decimal part. How could I get desired value working in GMP environment?

How to properly configure Livewire in a project? (after unsuccessfully trying to do it)

A few words about the site:

A website made with Laravel 11 is an online e-cigarette store. After I configured the general functionality of the site and the cart, there was a need to make the page not reload every time I click on the cart button, or remove an item from the cart.

The code part (don’t judge too harshly, I wanna to improve myself)

  1. Method index() that works with index.blade.php
    ProductsController:
public function index()
    {
        $cigarettes = Cigarette::all();
        $liquids = Liquid::all();
        $cart = Cart::content();
        $total = Cart::priceTotal(); 

        return view('index', compact('cigarettes', 'liquids','cart', 'total'));
    }

2.A part of the code that is responsible for displaying goods (cigarettes and liquids)

index.blade.php:

<div class="grid">
                    {{-- Cigarettes --}}
                    @forelse($cigarettes as $cigarette)
                        <x-cigarette-card :cigarette="$cigarette"
                                          :cart="$cart"
                        />
                    @empty
                        <div class="#">
                            No cigarettes in the database
                        </div>
                    @endforelse

                    {{-- Liquids --}}
                    @forelse($liquids as $liquid)
                        <x-liquid-card :liquid="$liquid"
                                       :cart="$cart"
                        />

                    @empty
                        <div class="#">
                            No liquids in the database
                        </div>
                    @endforelse
                </div>

(i know that include $cart variable into component with code for product isn’t really fancy, but its my first big project)

3.Code of my components:
components/cigarette-card.blade.php:
@props([‘cigarette’, ‘cart’])

<div class="grid__item">
    <article class="product {{ $cigarette->type }}">
        {{-- Image --}}
        <img class="product__image" src="{{ asset('./storage/' . $cigarette->image) }}" alt="{{ $cigarette->name }}" />

        <div class="product__description">
            {{-- Name --}}
            <h2 class="product__name">{{ $cigarette->name }}</h2>
            {{-- Info --}}
            <div class="product__info">
                ✔&nbsp;Moc - {{ $cigarette->strength }}%
                <br>
                ✔&nbsp;{{ $cigarette->puffs }} zaciÄ…gnięć
                <br>
                ✔&nbsp;Smak: {{ $cigarette->flavor }}
            </div>
            {{-- Price --}}
            <p class="product__price">Cena: {{ $cigarette->price }} zł</p>
        </div>

{{-- Buttons for guests: [Buy] [Delete from cart] [Add to cart] --}}
@guest...@endguest

{{-- Buttons for admins: Admin Panel: [Delete product] [Edit page button] [Show page button] --}}
@auth...@endauth
</article>
</div>

<div>
    {{ $slot }}
</div>

And I’d like to show a form for adding product in cart:
(THIS CODE IS SIMILAR FOR liquids)

components/cigarette-card.blade.php

                {{-- Cart button --}}
                <form action="{{ route('cart.store') }}" method="POST">
                    @csrf

                    {{-- Quantity control --}}
                    <div class="quantity-control">
                        <button type="button" class="quantity-button decrease">-</button>

                        <input type="number" name="quantity" class="quantity-input" 
                        value="1" min="1" readonly/>

                        <button type="button" class="quantity-button increase">+</button>
                    </div>

                    {{-- Product id --}}
                    <input type="hidden" name="product_id" value="{{ $cigarette->id }}">
                    <input type="hidden" name="type" value="cigarette">

                    {{-- Cart button submit (with an image) --}}
                    <button type="submit" 
                     class="button product__button" aria-label="Dodaj do koszyka">

                        <svg class="button__icon" width="20" height="20">
                            <use href="./storage/images/footer-icons/symbol-defs.svg#icon-shopping-cart"></use>
                        </svg>
                    </button>
                </form>

Also I wanna to show a delete from cart form:

                {{-- Delete from cart --}}
                <form action="{{ route('cart.delete') }}" method="POST">
                    @csrf
                    <!-- rowId -->
                    <input type="hidden" name="rowId" value="{{ $cart->where('id', $cigarette->id)->first()->rowId }}">
                    <!-- Product id -->
                    <input type="hidden" name="product_id" value="{{ $cigarette->id }}">
                    <!-- Type -->
                    <input type="hidden" name="type" value="cigarette">

                    <!-- Delete from cart button -->
                    <button type="submit" class="#">Delete from cart</button>
                </form>

Those parts of code (forms are similar for liquids)

What did I try:

First try: After installing Livewire I created two separate components for cigarettes and liquids, then after moving their code to the livewire component I made another livewire component that stored the code for the product (so the cigarette-card and liquid-card code was now in the livewire component, in other words I had a component within a component). After I edited the code in the methods of these components I was still getting page reloads

Second try: After that I decided to do things a bit differently, I made one livewire component, in which I put the code:

<div class="grid">
                    {{-- Cigarettes --}}
                    @forelse($cigarettes as $cigarette)
                        <x-cigarette-card :cigarette="$cigarette"
                                          :cart="$cart"
                        />
                    @empty
                        <div class="#">
                            No cigarettes in the database
                        </div>
                    @endforelse

                    {{-- Liquids --}}
                    @forelse($liquids as $liquid)
                        <x-liquid-card :liquid="$liquid"
                                       :cart="$cart"
                        />

                    @empty
                        <div class="#">
                            No liquids in the database
                        </div>
                    @endforelse
                </div> 

in this component I stopped using the code of cigarette-card and liquid-card components, i.e. now the code that used to be in the components appeared in the livewire component (this added difficulties, because the code became many times more). After reusing the livewire component's livewire method, I was still getting page reloads. 

My opinion:
My theory of what the problem is: maybe the problem lies in the fact that my project uses js code to open and close the cart page, which is a modal window.

Can anyone tell me how can I use Livewire in my project?