Accessing Javascript values defined in assets/js/app.js in Elixir

Hello, i want to know how can i possibly access/get Javascript values defined in assets/js/app.js into my Elixir code?

Example, in assets/js/app.js file…

var x = "hello"

What i want to happen or trying to accomplish is access this variable x’s value and pass it as parameter to my Elixir code defined in lib/app/test.ex.

Example Elixir code would be,

def my_function(x_value_here) do
	. . .
end

Any suggestion would be really appreciated. Thanks in advance :pray:

You might need to give more specific information on your goal, and whether youre using liveview or normal views and when you want to access the value.

1 Like

Hello sir, thank you for the response.

I am just using ordinary view.

What i’m currently doing here is i want to add a qr code scanner on my personal website (for test purposes only) and im using a Javascript library.

Now the Javascript code that reads and decodes the qr code was defined in assets/js/app.js file. I would want to access this result in my Elixir code so i can use it to scan for records in my database.

You wont be able to directly access the javascript values in Elixir, you need to send them over some bridge. There are a few ways you might approach this. Your QR library will have some way to run a javascript function when a QR code is recognised and this function will all most certainly receive the data that was embedded in the QR code.

In this callback you might:

a) Make a HTTP request in JS to a controller-action that returns data from your records. Your JS should then process the results and update the page for the user. Most commonly this data is returned as JSON.

Things you may want to look into: json, rest api and see Using the Fetch API - Web APIs | MDN which has some example JS code, as well as searching for phoenix rest api.

b) Redirect to a URL with your QR result embedded in the URL. So if your QR code decodes to dogs, you might redirect to https://myapp.com/search?q=dogs to search for dogs, or if it decoded to a record id 100, you might redirect to https://myapp.com/blog/100. This can be as simple as

window.location.href = `https://myapp.com/${qrdata}`;

c) Use the QR data to set values in a regular HTML form and submit it. This an be useful if you have an existing form on the page and the QR code is a “shortcut” to some results from that form.

Good luck. Try making all 3 options.

2 Likes

Thank you so much sir. I really appreciated your efforts! This are really very helpful to me :heart:

I’d also add using channels and/or liveview to the list of options you could use to send the value to the server for processing.

1 Like

Noted sir. Thank you :heart:

Would you mind explaining this further please? I have the same issue as the OP and am still new to elixir/phoenix. I’m using Surface UI if it helps to mention that. Thank you

1 Like