use php inside JavaScript

2019-08-20 03:22发布

I have an ajax function that post to an PHP file. Now since I'm using WordPress I can use the get_url function so I don't need to hard code the entire URL.

The WordPress function is an PHP so I'm trying to use PHP inside the ajax post. But it wont do the trick. Any ideas ? and is it possible ?

This is what I have.

$(document).ready(function(){

$('#submit').click(function(){

$.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(),  function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;

});

});

I have also tried the php echo inside quotes like this.

   $.post(' "<?php echo get_template_directory_uri(); ?>" /send.php' ....

ether way I get this path

http://mysite.com/%27%3C?php%20echo%20get_template_directory_uri();%20?%3E%27/send.php&email=&message=&name=&sent=1

1条回答
聊天终结者
2楼-- · 2019-08-20 03:54

Javascript to PHP = nope you cant embed javascript to php, only php can embed html and javascripts.

the better way to do it is to create a .php file and insert the javascript there...

Example: js.php

<?php
    function doSubmit() {
        ?>
        <script>
            $('#submit').click(function(){
                $.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(), function(response) {
                    $('#success').html(response);
                    //$('#success').hide('slow');
                    });
                return false;
            });
        </script>
        <?php
    }
?>

call the js.php using "include(js.php);" and call the functions inside another php

Inside your index.php

<?php
include('js.php');
?>
<html>
    <head><script><?php doSubmit();?></script></head>
    <body>
    </body>
</html>
查看更多
登录 后发表回答