1

I know this question already asked several times before. But i could not get related to me .I am working on chat system where i am sending and receiving messages.

My PHP code is :-

     <div class="chat-area" id="chatBox">
                    <?php
                    if (!empty($chats)) {
                        foreach ($chats as $chat) {
                            $timeago = get_timeago(strtotime($chat['created_at']));
                            $msg_time = htmlspecialchars(trim($timeago));
                            if ($chat['from_id'] == $_SESSION['login']) { ?>
                                <div class="outgoing">
                                    <div class="details">
                                        <p><?= $chat['message'] ?> <h><?= $msg_time ?></h>
                                        </p>
                                    </div>
                                </div>
                            <?php } else { ?>
                                <div class="incoming">
                                    <div class="details">
                                        <p> <?= $chat['message'] ?> <h><?= $msg_time ?></h>
                                        </p>
                                    </div>
                                </div>
                        <?php }
                        }
                    }

My js code is :-

    $(document).ready(function() {
            $("#sendBtn").on('click', function() {
                message = $("#message").val();
                if (message == "") return;

                $.post("app/ajax/insert.php", {
                        message: message,
                        to_id: <?= $unid ?>},
                    function(data, status) {
                        $("#message").val("");
                        $("#chatBox").append(data);
                        scrollDown();
                    });
            });

But the problem is when

     to_id: <?= $unid ?>

$unid is numeric like 12345 it working fine but when $unid is albhanumeric like 1b3vc3g its showing mention error. It is behaving same for send and receiving. Please help me to tackle this . thanks in advance

Bittu
  • 51
  • 1
  • 7
  • If the value can contain non-numeric characters then simply you need to put `to_id: '= $unid ?>'` so it's treated as a string by JS. – ADyson Mar 23 '22 at 09:12

1 Answers1

2

Use json_encode, which will output the correct form for JavaScript as long as the parameter is of one of the JSON-friendly types:

to_id: <?= json_encode($unid) ?>
Amadan
  • 191,408
  • 23
  • 240
  • 301