Javascript Assistance Required - Execute JS Script after Server Action Executed

Hi there JS gurus...

I need to execute a javascript script and pass in a value from a server action, kinda like this:

<script src="https://www.paypal.com/sdk/js?client-id={{get_activity.data.pp_client_id}}"></script>

Therefore I need to prevent the script from being executed until the server action has run.

Any ideas how I would do this?

Thanks!
Antony.

Hey Antony!

When you need this javascript to be executed?

If you can wait first for get_activity serverconnect to be executed and have results, you can call this javascript function on the success event of the serverconnect
(in a flow, run javascript)

ahhh script.. not a function

@Antony, Can we use a Conditional region in that case?
And the condition is the serverconnect...

Hey @famousmag , thanks for your reply!

Yes, I can wait until get_activity has run... but as you have just said, it is a script.

I'm just googling how to dynamically load scripts from a function... I think there may be a way to experiment with!

I have tried putting the <script> in a Wappler conditional region, but it seems to execute even when the condition is false...

Maybe you can try something like:

  <script>
    function loadPaypal() {
      const script = document.createElement('script');
      script.src = `https://www.paypal.com/sdk/js?client-id=`+dmx.parse('get_activity.data.pp_client_id');
      document.head.appendChild(script);
    }
  </script>

and call loadPaypal() on done event of the server action ondone="loadPaypal()"

2 Likes

You are a genius @Teodor, that works perfectly.

Thank you so much!

For anyone doing this with Paypal, once this sdk script has loaded, you have to load your own local script... so I have used an event listener to do that... here is the complete script:

 <script>
    // loadPaypal function - loads the scripts
    function load_paypal() {
      const sdk_script = document.createElement('script');
      sdk_script.src = `https://www.paypal.com/sdk/js?components=buttons,card-fields&client-id=`+dmx.parse('get_activity.data.pp_client_id');
      document.head.appendChild(sdk_script);
     const local_script = document.createElement('script');
      local_script.src = `paypal.js?x=`+dmx.parse('now_timestamp.value');
    
	  // check that they loaded... and call the local one once the SDK has loaded...
	  sdk_script.addEventListener("load", () => {
	  	console.log("Paypal SDK script loaded");
      document.head.appendChild(local_script);
	  });
	  local_script.addEventListener("load", () => {
	  	console.log("Paypal LOCAL script loaded")
	  });
	  sdk_script.addEventListener("error", (ev) => {
		  console.log("Error on loading paypal SDK script", ev);
	  });
	  local_script.addEventListener("error", (ev) => {
		  console.log("Error on loading paypal LOCAL script", ev);
	  });
  }
  </script>
5 Likes