Pass PHP variable to "file" javascript

Asked

Viewed 1,250 times

-4

I can pass a variable PHP for javascript if it is on the same page, but the problem is that if I throw this code to a file JS it doesn’t work.

  • The variable page brings?

2 answers

5


Yes you can do as long as javascript is not coming from an external source.

PHP page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">var param = "<?= $pagina ?>";</script>

<script type="text/javascript" src="js/paginacao.js"></script>

paginacao.js

jQuery(document).ready(function(){
    var pagina = param;
    jQuery('#btnpaginas').click(function(){
        pagina++;
        var dados = jQuery( this ).serialize();

        jQuery.ajax({
            type: "POST",
            url: "paginacao.php?pagina="+pagina,
            data: dados,
            success: function(data)
            {
                $(".paginacao").html(data);

            }
        });
        return false;
    });
});

1

I believe that there is no way to pass variables of the PHP to an archive .js external and static, since the processing is done in the file itself .php that is being executed.

  • Believe me. I don’t think it’s a problem for you to leave your code inside <script> same. If you look at the source code of sites like Google, Facebook, etc, you will always have some script thus. :)

Browser other questions tagged

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