How to run a Script using AJAX

Asked

Viewed 77 times

0

I have a form on a "pagina1.php" page, so:

<form id="form1" action="pagina2.php"
</form>

After running an Ajax function, I add the following script into this form with . append():

<script id='mp_script'  src="https://www.mercadopago.com.br/integrations/v1/web-payment-checkout.js"
data-preference-id="9999999">
</script>

Only that this Script does not run, as I do to run it after adding it with Ajax?

Obs. I cannot add this script any other way than with AJAX, as the "data-preference-id" attribute will change depending on what the user selects on the screen.

1 answer

1


You can use the method document.createElement to create the <script> and then insert it into the body of the page:

function createScript(src, attrs = {}) {
  // Criamos o `<script>`:
  const script = document.createElement('script');
  
  // Adicionamos os atributos customizados que recebemos pelo primeiro parâmetro:
  Object.entries(attrs).forEach(
    ([key, val]) => script.setAttribute(key, val)
  );
  
  // Origem do `<script>`:
  script.src = src;

  // Inserimos o `<script>` na página:
  document.body.appendChild(script);
}

createScript('https://lffg-archive.github.io/sopt/alert.js');

And to add a custom attribute to the created script, just use the second argument of the function we created. For example:

createScript('https://lffg-archive.github.io/sopt/alert.js', {
  'data-preference': '9999'
});

Suggested reading

Browser other questions tagged

You are not signed in. Login or sign up in order to post.