简体   繁体   中英

Incorrect value in javascript from PHP variable

I just want to start by saying I am not a JavaScript developer, I am new to this.

Ok, so, I have a session value called id, this is a long (example: 76561198237133252) and I am passing this as a argument for a method. The issue is the id is not correct when the function is actually ran.

JS:

function sendMessage(id) 
{
    var message = $("#message").val();
    if (message)
    {
        $.ajax(
        {
            url: 'addChatMessage.php', 
            type: 'POST', 
            data: '&id=' + id+ '&message=' + message, 
            dataType: 'text', 
            success: function (data) 
            {
                $('#chatMessages').load(document.URL +  ' #chatMessages');
                document.getElementById('message').value = '';
                $('#chatScrollable').animate({scrollTop:$(document).height()}, 1000);

                window.alert("Id: " + id);
            }
        });
    }
}

Html:

<div class="chat-input">
    <div class="input-group">
        <input type="text" id="message" class="form-control" placeholder="Message..." required>
        <!-- <input type="hidden" id="id" value="<?php //echo $_SESSION['id']; ?>"> -->
            <span class="input-group-btn">
                <button class="btn btn-default" id="msgButton" type="button" onclick="sendMessage(<?php echo $_SESSION['id']; ?>);">Send</button>
            </span>
        </div>
    </div>

Any help is appreciated.

Use json_encode() in PHP to convert a PHP value to the corresponding Javascript literal. It will encode it properly to keep the same data type (eg putting quotes around a string).

<button class="btn btn-default" id="msgButton" type="button" onclick="sendMessage(<?php echo htmlentities(json_encode($_SESSION['id'])); ?>);">Send</button>

You also need to use htmlentities() to convert the quotes around the string to entities. Otherwise, the quote will match the quote after onclick= , and end the attribute.

Javascript is both awesome and aggravating for this one reason: it auto-converts strings and numbers to make sense of impossible statements. Your id is a number, so it might not be converting to a string properly. Use the .toString() of id to fix this problem.

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