Code issues - Remote Event Not Firing Upon Button Press

'Hello everyone! I need a hand please :pray: For many days I’ve been trying to solve this problem, the bug or issue I have in my code is related to fireserver. When I press the deliveryOrderButton button in my code, the function is supposed to execute. The problem I’m having is that deliverOrderEvent:FireServer(order.username, order.item1, order.item2, order.totalprice) is not being executed, and it’s quite strange because everything seems to be done correctly. It’s a peculiar problem; I’ve searched and tried a thousand solutions, but the problem still persists. Any ideas on what could be hindering this or why it’s not executing properly? :pray:

In summary: The fireserver called “deliverOrderEvent” is not being executed when pressing the button.

Console output:

Organization of my project:

localscript:

-- Function to process and deliver orders for nearby customers
local function processAndDeliverOrderForCustomer(nearbyCustomer, orders)
	for _, order in pairs(orders) do
		if order.username == nearbyCustomer then
			print("Order Details:")
			print("Username:", order.username)
			print("Item 1:", order.item1)
			print("Item 2:", order.item2)
			print("Total Price:", order.totalprice)

			-- Print the data being sent to the server
			print("Sending order data to server:")
			print(order)

			-- Check if the deliverOrderEvent exists
			local deliverOrderEvent = ReplicatedStorage:FindFirstChild("deliverOrder")
			if deliverOrderEvent then
				-- Fire the deliverOrderEvent with the order details as parameters
				print("Delivering order...")
				deliverOrderEvent:FireServer(order.username, order.item1, order.item2, order.totalprice)
			else
				warn("deliverOrderEvent not found in ReplicatedStorage.remoteEvents")
			end
			break
		end
	end
end

-- Connect the MouseButton1Click event for the deliveryOrderButton
deliveryOrderButton.MouseButton1Click:Connect(function()
	-- Handle the delivery order button click
	print("Delivery order button pressed")

	-- Get the order data and process the order
	local orderData = saveOrderData()
	processOrder(orderData)

	-- Check if there is an order for the nearby customer
	local nearbyCustomer = checkNearbyCustomer() 
	local orderExistsForCustomer = checkOrderExists(nearbyCustomer) 

	if orderExistsForCustomer then
		-- Process and deliver the order for the nearby customer
		processAndDeliverOrderForCustomer(nearbyCustomer, orders)
	else
		print("No order found for nearby customer:", nearbyCustomer)
	end
end)

server-side-script (for deliverOrder remote event):

-- Get the RemoteEvent for delivering orders from the client
local replicatedStorage = game:GetService("ReplicatedStorage")
local deliverOrderEvent = replicatedStorage:WaitForChild("deliverOrder")

deliverOrderEvent.OnServerEvent:Connect(function(player, username, item1, item2, totalPrice)
	print("Received order data from the client for player:", player.Name)
	print("Username:", username)
	print("Item 1:", item1)
	print("Item 2:", item2)
	print("Total Price:", totalPrice)
end)

print("Server script loaded successfully.")

Full localscript code:

-- Import necessary services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

-- Get the remote event for sending order information
local orderInfoEvent = ReplicatedStorage.remoteEvents:WaitForChild("orderInformationEvent")

-- Get the remote event for updating orders
local orderUpdateEvent = ReplicatedStorage.remoteEvents:WaitForChild("OrderUpdateEvent")

-- Get the player's GUI
local playerGui = Players.LocalPlayer:WaitForChild("PlayerGui")

-- Find the button within the PlayerGui hierarchy
local deliveryOrderButton = playerGui:WaitForChild("Order_Delivery"):WaitForChild("deliveryOrderButton")
local orderTextInfo = playerGui:WaitForChild("Order_Delivery").orderTextInfo

-- Define variables
local buttonsFolder = script.Parent
local hideGuiButton = buttonsFolder.Parent.OrderFrame.NoTextButton
local totalCostTextLabel = buttonsFolder.Parent.OrderFrame.TotalCostText
local buttonYesRequestOrder = buttonsFolder.Parent.OrderFrame.YesTextButton
local textOrdersNames = {
	buttonsFolder.Parent.OrderFrame.OrderName1Text,
	buttonsFolder.Parent.OrderFrame.OrderName2Text
}
local clickedButtons = {}

-- Define buttons and their associated names
local buttonNames = {
	BurgerTextButton = "Burger",
	DonutTextButton = "Donut",
	FriesTextButton = "Fries",
	SliceOfCakeTextButton = "Slice of Cake",
	SodaTextButton = "Soda",
	WaterTextButton = "Water"
}

-- Define prices for each button
local buttonPrices = {
	BurgerTextButton = 5,
	DonutTextButton = 3,
	FriesTextButton = 4,
	SliceOfCakeTextButton = 6,
	SodaTextButton = 2,
	WaterTextButton = 1
}

-- Function to toggle loading order sent GUI
local function toggleLoadingOrderSent(enabled)
	-- Toggle the loading order sent GUI visibility
	Players.LocalPlayer.PlayerGui.loading_order_sent.Enabled = enabled
end

-- Function to update order name displayed
local function updateOrderName(button, index)
	-- Update the displayed order name based on the button clicked
	local orderNameText = textOrdersNames[index]
	if orderNameText then
		orderNameText.Text = button.Text
	end
end

-- Function to calculate total price of selected items
local function calculateTotalPrice()
	-- Calculate the total price of selected items
	local totalPrice = 0
	for _, clickedButton in ipairs(clickedButtons) do
		local price = buttonPrices[clickedButton.Name]
		totalPrice = totalPrice + price
	end
	return totalPrice
end

-- Connect click events for each button
for _, button in pairs(buttonsFolder:GetChildren()) do
	if button:IsA("TextButton") then
		-- Connect click events for each button to handle order selection
		button.MouseButton1Click:Connect(function()
			if #clickedButtons < 2 then
				table.insert(clickedButtons, button)
				updateOrderName(button, #clickedButtons)
				totalCostTextLabel.Text = "Total Cost: $" .. calculateTotalPrice()
				-- Change button background color to green to indicate selection
				button.BackgroundColor3 = Color3.fromRGB(0, 255, 0) -- Green color
			end
		end)
	end
end

-- Function to reset button color
local function resetButtonColor()
	-- Reset the color of all buttons to their original color
	for _, button in ipairs(buttonsFolder:GetChildren()) do
		if button:IsA("TextButton") then
			button.BackgroundColor3 = Color3.fromRGB(211, 211, 211) -- Original color
		end
	end
end

-- Function to reset the order
local function resetOrder()
	-- Reset the order selection and displayed information
	clickedButtons = {}
	for _, orderNameText in ipairs(textOrdersNames) do
		orderNameText.Text = "..."
	end
	totalCostTextLabel.Text = "Total Cost: $0"
end

-- Connect click event for hide GUI button
hideGuiButton.MouseButton1Click:Connect(function()
	-- Reset the order and hide the GUI
	resetOrder()
	ReplicatedStorage.remoteEvents:WaitForChild("close_OrderGUI"):FireServer()
	resetButtonColor() -- Reset button color
end)

-- Define the orders table if it doesn't exist
local orders = {}

-- Function to get order data when buttonYesRequestOrder is pressed
local function saveOrderData()
	-- Gather information about the selected items and calculate total cost
	local selectedItems = {}
	for _, button in ipairs(clickedButtons) do
		local itemName = buttonNames[button.Name]
		if itemName then
			table.insert(selectedItems, itemName)
		end
	end
	local totalCost = calculateTotalPrice()

	-- Create the order object
	local order = {
		username = Players.LocalPlayer.Name, -- Include the username of the player
		item1 = selectedItems[1] or "",
		item2 = selectedItems[2] or "",
		totalprice = totalCost
	}

	-- Add the order to the orders table
	table.insert(orders, order)

	-- Notify the server about the new order
	orderUpdateEvent:FireServer(order)

	return order -- Return the order table
end

-- Function to check nearby customer
local function checkNearbyCustomer()
	-- Check if there is a customer nearby and return their username if found
	local maxDistance = 15 -- Maximum distance to consider a player as nearby (adjust as needed)
	local player = game.Players.LocalPlayer
	local nearbyCustomer = ""

	for _, otherPlayer in ipairs(game.Players:GetPlayers()) do
		if otherPlayer ~= player and otherPlayer.Team.Name == "Customer" then
			local character = otherPlayer.Character
			if character and character:FindFirstChild("HumanoidRootPart") then
				local distance = (character.HumanoidRootPart.Position - player.Character.HumanoidRootPart.Position).magnitude
				if distance <= maxDistance then
					nearbyCustomer = otherPlayer.Name -- Set the nearby customer username
					break
				end
			end
		end
	end

	return nearbyCustomer
end

-- Function to update the order text based on nearby customer
local function updateOrderText()
	-- Update the order text based on the nearby customer's presence
	local nearbyCustomer = checkNearbyCustomer()
	if nearbyCustomer == "" then
		orderTextInfo.Text = "You are holding the Order of ... in your hands. Place the Tray/Plate on a green spot on the tables."
	else
		orderTextInfo.Text = "You are holding the Order of " .. nearbyCustomer .. " in your hands. Place the Tray/Plate on a green spot on the tables."
	end
end

-- Call the updateOrderText function periodically to keep the order text updated
local function updateOrderPeriodically()
	-- Continuously update the order text to reflect nearby customer presence
	spawn(function()
		while true do
			updateOrderText()
			wait(1)
		end
	end)
end

-- Function to check if the order exists in the orders table
local function checkOrderExists(username)
	-- Check if an order exists for a given username
	print("Checking if order exists for username:", username)
	for _, order in pairs(orders) do
		if order.username == username then
			print("Order found for username:", username)
			return true -- Order found
		end
	end
	print("Order not found for username:", username)
	return false -- Order not found
end

-- Listen to the remote event to receive order update notifications
orderUpdateEvent.OnClientEvent:Connect(function(orderData)
	-- Update the client's UI with the new order data
	table.insert(orders, orderData)  -- Add the order to the local orders table
end)

-- Function to process the order data
local function processOrder(orderData)
	-- Process the order by sending it to the server and displaying loading animation
	local totalPrice = calculateTotalPrice()

	if totalPrice > 0 then
		resetOrder()
		ReplicatedStorage.remoteEvents:WaitForChild("close_OrderGUI"):FireServer()
		toggleLoadingOrderSent(true)
		wait(3)
		toggleLoadingOrderSent(false)
		wait(0.2)

		local playerTeamName = Players.LocalPlayer.Team and Players.LocalPlayer.Team.Name
		if playerTeamName == "Customer" then
			local clonedTemplateEvent = game:GetService("ReplicatedStorage").orderTemplate:WaitForChild("clonedTemplateEvent")
			-- Pass order data as parameters to clonedTemplateEvent:FireServer()
			clonedTemplateEvent:FireServer(orderData.username, orderData.item1, orderData.item2, orderData.totalprice)
		else
			print("You are not in the Customer Team.")
		end
		resetButtonColor() -- Reset button color
	else
		warn("There are no items in the order or a template already exists.")
	end
end

-- Connect click event for yes request order button
buttonYesRequestOrder.MouseButton1Click:Connect(function()
	-- Process the order when the "Yes" button is clicked
	local orderData = saveOrderData()
	processOrder(orderData)
end)

-- Function to process and deliver orders for nearby customers
local function processAndDeliverOrderForCustomer(nearbyCustomer, orders)
	for _, order in pairs(orders) do
		if order.username == nearbyCustomer then
			print("Order Details:")
			print("Username:", order.username)
			print("Item 1:", order.item1)
			print("Item 2:", order.item2)
			print("Total Price:", order.totalprice)

			-- Print the data being sent to the server
			print("Sending order data to server:")
			print(order)

			-- Check if the deliverOrderEvent exists
			local deliverOrderEvent = ReplicatedStorage:FindFirstChild("deliverOrder")
			if deliverOrderEvent then
				-- Fire the deliverOrderEvent with the order details as parameters
				print("Delivering order...")
				deliverOrderEvent:FireServer(order.username, order.item1, order.item2, order.totalprice)
			else
				warn("deliverOrderEvent not found in ReplicatedStorage.remoteEvents")
			end
			break
		end
	end
end

-- Connect the MouseButton1Click event for the deliveryOrderButton
deliveryOrderButton.MouseButton1Click:Connect(function()
	-- Handle the delivery order button click
	print("Delivery order button pressed")

	-- Get the order data and process the order
	local orderData = saveOrderData()
	processOrder(orderData)

	-- Check if there is an order for the nearby customer
	local nearbyCustomer = checkNearbyCustomer() 
	local orderExistsForCustomer = checkOrderExists(nearbyCustomer) 

	if orderExistsForCustomer then
		-- Process and deliver the order for the nearby customer
		processAndDeliverOrderForCustomer(nearbyCustomer, orders)
	else
		print("No order found for nearby customer:", nearbyCustomer)
	end
end)


-- Start updating the order text periodically
updateOrderPeriodically()