简体   繁体   中英

PHP base URL in external js file

I have few JS in HTML page, if I use this in HTML view file then its working fine, my page submit form correctly without any issue.

But when I moved this JS codes to external JS file, then it shows error,

Below is my JS

$("#user_fm").submit(function (event) {
    event.preventDefault();
        $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>index.php/admin/peoples/add_user",
            data: $("#user_fm").serialize(),
-----

my problem is clear to me, that in view page this is easily get decoded to my url

"<?php echo base_url(); ?>index.php/admin/peoples/add_user"

but when i keep this in JS file it show like below in console,

POST http://localhost/center/index.php/admin/peoples/%3C?php%20echo%20base_url();%20?%3Eindex.php/admin/peoples/add_user

How can we put PHP codes in JS file?

To be able to embed PHP in html or javascript code, like <?php echo base_url();?> , the file must have .php extension, while your external javascript file certainly has .js extension. Besides .js files are parsed by the browser, while PHP files must be executed on the server.

What you can do is to first define a variable in inline javascript, and then use it in code of external .js files. In index.php or whatever main file you use, place this before you use your external js code:

<script type="text/javascript">
var baseURL = "<?php echo base_url(); ?>";
</script>

And then in your external code:

$("#user_fm").submit(function (event) {
    event.preventDefault();
        $.ajax({
            type: "POST",
            url: baseURL + "index.php/admin/peoples/add_user",
            data: $("#user_fm").serialize(),
-----

clearly you cant access. Run your script with XXAMP YOU need to turn apache service on so that php can read YOUR base URL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM