简体   繁体   中英

Change php include path with javascript

I'm trying to change the include path of a php file with javascript if the user changes the language of the website.

I'm using this code to check if the language of the website is english or not.

<script type="text/javascript">
        $(function() {
            var pathname = window.location.pathname;
            if (pathname.search('/en/') != -1){
                //I wanna insert the new path here
            }
        });
    </script>

And then I wanna change the include function from

<?php include 'navigation.php'; ?>

to

<?php include 'navigation_en.php'; ?>

Does anybody know how to make this work? Or do I have to check the pathname with php to change the php include function?

You cannot do this with pure javascript, because javascript is executed after the php processing completes. You can do the same thing with pure PHP though:

$uri = $_SERVER['REQUEST_URI'];
if(preg_match('/^\/en\//', $uri)) {
    include_once('include_en.php');
}
else {
    include_once('include.php');
}

This code assumes that your URL's would be in the form http://www.mydomain.com/en/some/page.php

EDIT:

As this code runs inside wordpress, $_SERVER['REQUEST_URI ] does not return the language part. Thanks to the OP, the way to do it in wordpress would be:

$lang = get_bloginfo('language');
if(preg_match('/^\/en-/', $lang)) {
    include_once('include_en.php');
}
else {
    include_once('include.php');
}

You cannot use just JavaScript alone to change the variables in PHP. But you can do one thing. You can use AJAX Queries, when the value of the <select> tag changes, by firing a request to the server.

$("select.language").change(function(){
    $.ajax({
        url: 'changeLang.php?lang=' + $(this).val(),
        success: function(data) {
            alert("Successfully set the language to " + data);
        }
    });
});

In the backend PHP Code, you can do this way:

if(isset($_GET["lang"]))
    // Set the lang.
    die("English");

I'm fairly certain this isn't possible, since the PHP generates markup before it's sent to the client. Another solution would be to reload the page with JavaScript, and include some kind of parameter in the URL which then tells PHP which include tag to use.

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