Well, there are actually 2 ways for the lua script to communicate with nui. The first is to pass the message from the client.lua to the UI side, and the second way is to make a callback from the UI side to the client and then back to the UI (kinda hard to understand, especially the second way, but I hope you will understand it with code example).
So, the first way - SendNUIMessage
(There are actually two functions - SendNUIMessage
(NUI
) and SendNuiMessage
(Nui
) - yeah it is a difference, the first function’s argument is table, and the second function’s argument is json string, so for me it is better to use the first function).
Sending message to UI page from client script
SendNUIMessage({ -- you can add here as many table's keys as you want
action = "log something",
value = 123,
anything = "foo",
another = true
})
Handling sent message on UI page (script.js)
window.addEventListener("message", function(event){
let e = event.data;
if(e.action == "log something"){
console.log("Logging something, btw the value is equal to " + e.value);
}
})
The 2nd way is to pass message from nui, to client - it is possible via fetch
(it is explained here NUI callbacks - Cfx.re Docs)
Fetching message
fetch(`https://${GetParentResourceName()}/YOUR_CALLBACK_NAME`, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
anything: "anything",
value: 54321
})
});
^ this code sends “message” (to the client script) which is:
{
anything: "anything",
value: 54321
}
Handling callback on client side
RegisterNUICallback("YOUR_CALLBACK_NAME", function(data, cb)
print(data.anything)
print(data.value)
cb(true) -- always callback value, even if you won't use it
end)
Soo that’s all I think you need to pass messages from script to UI and vice versa, I hope I helped 