简体   繁体   中英

Echoing php inside javascript

Trying to display the message in a MySQL table to all users' screens using xmlhttp, toastr alert and php.

I use xmlhttp.open("GET","includes/ajax/user/general/messages.php?username=<?php echo $_SESSION['username']; ?>",true); which is where the SQL is and I put this on a 5 second loop so it checks messages.php every 5 seconds.

After I then do:

xmlhttp.send();

$.toast({
heading: <?php echo json_encode($messageInfo['title']); ?>,
text: <?php echo json_encode($messageInfo['message']); ?>,
position: 'top-right',
loaderBg: '#ff6849',
icon: <?php echo json_encode($messageInfo['type']); ?>,
hideAfter: 6000,
stack: 6
});

However this only outputs 'null' as the heading and 'null' as the text.

messages.php:

<?php

    if (!isset($_SERVER['HTTP_REFERER'])){
        die;
    }

    ob_start();
    require_once '../../../app/config.php';
    require_once '../../../app/init.php';

    if (!empty($maintaince)){
        die();
    }


    if (!($user -> LoggedIn()) || !($user -> notBanned($odb)) || !($user->isAdmin($odb))){
        die();
    }


    $username = $_GET['username'];

    if(empty($username)){
        die();
    }

    $SQLGetInfo = $odb -> prepare("SELECT * FROM `live_messages` WHERE id = 1");
    $SQLGetInfo -> execute(array($_SESSION['ID']));
    $messageInfo = $SQLGetInfo -> fetch(PDO::FETCH_ASSOC);

    $type = $messageInfo['type'];
    $title = $messageInfo['title'];
    $message = $messageInfo['message'];


?>

EDIT: If I put the PHP code which is in messages.php directly into the file which runs this script then it fetches from the database successfully however this is no help as i'm looking to display messages in real time.

EDIT: Full script

<script>

                window.setInterval(function(){

                    var xmlhttp;

                    if (window.XMLHttpRequest){

                        xmlhttp = new XMLHttpRequest();

                    }

                    else{

                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

                    }

                    xmlhttp.open("GET","includes/ajax/user/general/messages.php?username=<?php echo $_SESSION['username']; ?>",true);



                    xmlhttp.send();

                    $.toast({
                    heading: <?php echo json_encode($title); ?>,
                    text: <?php echo json_encode($message); ?>,
                    position: 'top-right',
                    loaderBg: '#ff6849',
                    icon: <?php echo json_encode($type); ?>,
                    hideAfter: 6000,
                    stack: 6
                    });


                }, 5000);


                </script>

I think you have slight misunderstanding of how to use XHR requests. XHR requests work similarly to browser requests, and with the code you've shown us you have no handler registered for the response.

See the POST example on MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

Now, in order to access the data processed by messages.php you're going to have to send back a proper JSON response.

IE header('Content-Type: application/json'); echo json_encode($messageInfo); header('Content-Type: application/json'); echo json_encode($messageInfo);

Which will then be passed back to your XHR requests load handler.

W3 Schools has an "okay" example of how its all put together: https://www.w3schools.com/js/js_json_php.asp

EDIT: I've provided a working code example that is essentially a direct copy and paste of the content in the w3schools link.

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script>
        var xmlhttp = new XMLHttpRequest();

        // When the XHR Request receives a response from the server
        // this function will be called.
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

                // This function is necessary to parse the JSON sent back
                // from the server.
                // Note: It can fail, so you'll want to make sure it actually parsed
                // the response.
                var message = JSON.parse(this.responseText);

                // Here is an example of how you would use it with your $.toast call
                // $.toast({
                //     heading: message.heading,
                //     text: message.body,
                //     position: 'top-right',
                //     loaderBg: '#ff6849',
                //     icon: message.type,
                //     hideAfter: 6000,
                //     stack: 6
                // });

                document.getElementById("toast_title").innerHTML = message.title;
                document.getElementById("toast_body").innerHTML = message.body;
            }
        };

        xmlhttp.open("GET", "demo_file.php", true);
        xmlhttp.send();
    </script>
</head>
<body>
    <div id="toast_title"></div>
    <div id="toast_body"></div>
</body>
</html>

demo_file.php

/**
 * All of your logic to get the messages
 */

$message = [
    'title' => 'This is basically the same thing as the W3 Schools link.',
    'body' => 'After JSON Encoding this array, and echoing it out it will be sent to your XHR requests onreadystatechange function'
];

// Its important that the call to header goes before ANY output.
// otherwise it will bomb.
header("Content-Type: application/json;");
echo json_encode($message);

may be

<script>
var username = "<?php echo $_SESSION['username']; ?>";
var title = JSON.parse("<?php echo json_encode($title); ?>");
var message = JSON.parse("<?php echo json_encode($message); ?>");
var type = JSON.parse("<?php echo json_encode($type); ?>");

window.setInterval(function(){

                var xmlhttp;

                if (window.XMLHttpRequest){

                    xmlhttp = new XMLHttpRequest();

                }

                else{

                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

                }

                xmlhttp.open("GET","includes/ajax/user/general/messages.php?username="+username ,true);



                xmlhttp.send();

                $.toast({
                heading: title,
                text: message,
                position: 'top-right',
                loaderBg: '#ff6849',
                icon: type,
                hideAfter: 6000,
                stack: 6
                });
            }, 5000);
</script>

I don't get why people who don't even know what the problem is are attempting answers at random, but:

<?php

        if (!isset($_SERVER['HTTP_REFERER'])){
              header("HTTP/1.0 404 Not Found")
                die('HTTP_REFERER is not set');
        }

        require_once '../../../app/config.php';
        require_once '../../../app/init.php';

        if (!empty($maintaince)){
              header("HTTP/1.0 404 Not Found")
                die('maintaince is not set');
        }


        if (!($user -> LoggedIn()) || !($user -> notBanned($odb)) || !($user->isAdmin($odb))){
              header("HTTP/1.0 404 Not Found")
                die('User not logged in, banned, or isn\'t an admin');
        }


        $username = $_GET['username'];

        if(empty($username)){
              header("HTTP/1.0 404 Not Found")
                die('username is not set');
        }

        $SQLGetInfo = $odb -> prepare("SELECT * FROM `live_messages` WHERE id = 1");
        $SQLGetInfo -> execute(array($_SESSION['ID']));
        $messageInfo = $SQLGetInfo -> fetch(PDO::FETCH_ASSOC);

        $type = $messageInfo['type'];
        $title = $messageInfo['title'];
        $message = $messageInfo['message'];

        echo json_encode(array(
            'type' => $type,
            'title' => $title,
            'message' => $message,
        ));
        exit();
?>

and

<script>

window.setInterval(function(){

        var xmlhttp;

        if (window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
        } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET","includes/ajax/user/general/messages.php?username=<?php echo $_SESSION['username']; ?>",true);

        xmlhttp.addEventListener("load", function () {
            if (xmlhttp.status === 200) {
                var res = JSON.parse(xmlhttp.responseText);
                $.toast({
                        heading: res.title,
                        text: res.message,
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: res.type,
                        hideAfter: 6000,
                        stack: 6
                });
            } else {
                $.toast({
                        heading: 'ERROR',
                        text: 'AN ERROR OCCURED' + xmlhttp.responseText,
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: '',
                        hideAfter: 6000,
                        stack: 6
                });
            }
        };

        xmlhttp.send();
}, 5000);


</script>

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