简体   繁体   中英

How to access PHP variables located in external PHP file within Javascript code?

I am a learning developer that is trying to utilize websockets, php and javascript to create a module for a web application I use. However, I am not sure if I can use the two languages together in such a way that I am doing as I am not very knowledgeable with Javascript yet.

What I would like to do is grab two strings located in a settings.php file, get those strings, convert those strings over to a Javascript string so that I can use what the PHP string value is as the Javascript variable. I tried to follow guides online and got this far with the browser console only showing

WebSocket connection to 'wss://%3C/?php%20echo%20$server_ip%20?%3E:%3C?php%20echo%20$server_port%20?%3E/websocket' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

Followed guides similar to this including this one to try to gain an understanding with no luck: https://www.dyn-web.com/tutorials/php-js/scalar.php

This guide was suggested as similar, but this involves an external Javascript file and not an external PHP file. This is totally different. Access PHP var from external javascript file

Here is the main code in question where I'll access the PHP variable in Javascript:

    <!--Include some variables from PHP settings file to fetch IP/port-->
    <?php include(ROOT_PATH . '/modules/Webchat/includes/settings.php'); ?>
    <?php echo $server_ip; ?>

    <script type="text/javascript">
        $(document).ready(function(){
            var socket;
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }
            if (window.WebSocket) {


                var ip = "<?php echo $server_ip ?>";
                var port = "<?php echo $server_port ?>";
                // TODO: Get socketAddress from settings.php


                var socketAddress = ip + (port ? ':' + port : '');


                var nextID = 0;
                var messageCount = 0;

                socket = new WebSocket("wss://" + socketAddress + "/websocket");

Here is my settings.php file where the PHP variables are stored:

<?php
$server_ip = $queries->getWhere('mc_servers', array('is_default', '=', 1));
$server_port = 25566;
$endpoint = "/websocket";
?>

I expect the output of the server_ip php variable to be a string such as "server.example.com". I expect the output of server_port to be 25566.

You could solve this by having the PHP file echo out the variables, then use javascript to request and load them.

Make sure that settings.php is accessible somewhere on the server and put

<?php
$server_ip = $queries->getWhere('mc_servers', array('is_default', '=', 1));
$server_port = 25566;
$endpoint = "/websocket";
header("Access-Control-Allow-Origin: *");
echo json_encode([$server_ip, $server_port, $endpoint]);
?>

The header keeps a CORS error from happening and then we encode the values as JSON.

<script type="text/javascript">
    $(document).ready(function(){
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            $.getJSON('/modules/Webchat/includes/settings.php') 
              .done(function setvars(data) {
                  server_ip = data[0];
                  server_port = data[1];
                  endpoint = data[2];
              })
              .fail(function (data) {
                  alert('Couldn't get server variables! ')
              });

            var socketAddress = ip + (port ? ':' + port : '');

            var nextID = 0;
            var messageCount = 0;

            socket = new WebSocket("wss://" + socketAddress + "/websocket");
</script>

What this code does is it uses $.getJSON to retrieve the encoded variables from settings.php as load then as javascript variables

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