benonymus

benonymus

Phoenix liveview with Stripe element not working

Hey there,

I have a liveview that is being live rendered inside a usual eex new template, and in this liveview I have this for stripe:

  <%= if @show_stripe_credit_form do %>
  <div class="field" phx-hook="Test">
    <%= label f, "Credit Card", class: "label" %>
    <div id="card-element" style="border: 1px solid #DFE0E0" class="b-r-4 p-2">
      <!-- Elements will create input elements here -->
    </div>

    <!-- We'll put the error messages in this element -->
    <p id="card-errors" role="alert" class="has-text-danger m-t-1">

    </p>
  </div>
  <% end %>

I also have a separate file with the js which works on another page of the app without liveview element, but it doesn’t seem to hook into this one. Here is the js:

<script src="https://js.stripe.com/v3/"></script>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    if (!document.getElementById('card-element')) {
      return
    }

    var stripe = Stripe('<%= System.get_env("STRIPE_PUBLISHABLE_KEY") %>');
    var elements = stripe.elements({
      fonts: [
        {
          cssSrc: 'https://use.typekit.net/gjk6uuk.css',
        },
      ],
    });

    var style = {
      base: {
        color: "#32325d",
        fontFamily: 'sofia-pro, avenir next, avenir, BlinkMacSystemFont, -apple-system, "Segoe UI", "Roboto", sans-serif',
      },
      invalid: {
        color: "#FF495C",
        iconColor: "#fa755a"
      }
    };

    var card = elements.create("card", { style: style });
    card.mount("#card-element");

    card.addEventListener('change', function(event) {
      var displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = event.error.message;
      } else {
        displayError.textContent = '';
      }
    });

    let form  = document.getElementById('ticket-order-form');
    console.log(form)
    let submitButton  = document.getElementById('submit-button');

    form.addEventListener('submit', (event) => {
      event.preventDefault()
      submitButton.disable = true;
      stripe.createToken(card).then(function(result) {
        if (result.error) {
          // show error
          errorElement = document.getElementById('card-errors')
          errorElement.textContent = result.error.message
          submitButton.disable = false;
        } else {
          // add stripeToken to form and submit
          stripeTokenHandler(result.token)
        }
      });
    });

    function stripeTokenHandler(token) {
      console.log(token)
      hiddenInput = document.createElement('input')
      hiddenInput.setAttribute('type', 'hidden')
      hiddenInput.setAttribute('name', 'stripeToken')
      hiddenInput.setAttribute('value', token.id)
      form.appendChild(hiddenInput)

      form.submit()
    }
  });
</script>

My question is where do I need to add this in order to be applied in the liveview every time the liveview changes, because I hide the field based on changes on the page?

Thanks!

Most Liked

sfusato

sfusato

Add another event listener like the one you have for DOMContentLoaded, but for phx:page-loading-stop and on the window object.

window.addEventListener('phx:page-loading-stop', () => {
   ...
});

See if this gets you closer to your objective. Then, since you say you need to react every time the liveview changes, you could properly hook it up via a liveview hook.

sfusato

sfusato

When you “live navigate” that piece of JS won’t be run again. For liveview pages, you could listen on this event: phx:page-loading-stop.

winescout

winescout

I had a similar issue getting some Bootstrap JS to register if they were injected into the page. With that page-loading-stop hook there, you still need to get all your markup loaded on the page before it fires. In the case that started this thread, that “<%= if … %>” is probably causing that code to render after some handle_event, and after the page-loading-stop callback.

In some cases, I’m able to use “display: none” and “display: block” instead so the code is loaded before the callback, but that doesn’t work in all cases unfortunately.

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement