How to call a function from a.js file in index.php itself in the script

Asked

Viewed 1,312 times

0

I wonder how, I call a function of a file x.js, on a page x.html x.php whatever it takes.

Example:

x.js file:

function myFunction(img){
    // Faz algo
}

index.php file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <script>

        myFunction("algo.jpg"); // <-- como fazer uma função de um arquivo js, aceitar eu chamar ela em um arquivo index.php?

    </script>
</head>
<body>
     <img src="img/algo.jpg" alt="">

     <script src="x.js"></script>
</body>
</html>
  • should include the file with <script src="x.js"></script>

  • this, but that’s not what I meant, I’m saying that even putting this, the above function does not work

  • For any other reason, it is not because of being php. What was supposed to function to do?

  • No, index.php was just an example could be . html . jsp anyway, I wish that when creating a function in a.JS FILE I could call this function in my.HTML FILE/PHP ETC by <script></script>, the point is, I need to pass images to this function, and each page will have a different image, then on each page I need to call this function passing as parameter the name of these images

  • The problem is not in calling the function. The example you have works perfectly regardless of being php, jsp, html or whatever, assuming you’re including the file js as I mentioned. If so, the problem is what you are trying to do specifically within the function, which is not working for you and leads you to believe that the function is not being called. Take advantage and confirm if you have errors in the browser, which should give you right away to rule out whether the file is being included correctly

  • The Wéllingthon M. de Souza, solved the problem, that’s all I needed, only I didn’t fill something so simple, thanks Isac, for trying to help me too

  • It was the first thing I started to indicate, the inclusion of the lol file, I naturally assumed that I knew where to put it

  • Yes kk, something so simple right, it was in my face and I didn’t notice, basic thing, but... it’s part.

Show 3 more comments

1 answer

1


This is very common here, and the question this order, you are trying to access a method that is not yet in the document, because you are importing the file Javascript at the end of the document.

Do the following place the line

<script src="x.js"></script>

Before:

<script>

    myFunction("algo.jpg"); // <-- como fazer uma função de um arquivo js, aceitar eu chamar ela em um arquivo index.php?

</script>

See working in plnkr.co

  • Bingo, it was on my face and I didn’t notice, basic thing of the basic, Thanks Wéllingthon !!

Browser other questions tagged

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