beadrex beadrex - 4 years ago 123
PHP Question

Pass PHP variable to JavaScript over AJAX (chat app)

heyo!

I'm trying to create a chat app for my website which has users (registration, login etc). I'm using NodeJS as the chat server so I can use SocketIO with it.

I have a index.php, in which I have set up a form with a text field and a submit button.
To retrieve the username I have this handy piece of code in the top:

$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);


So I can access the username by
$row['userName'];


I've done so as well in my insertMessage.php, so inserting the username with the message into the database works fine.
But I don't know how to figure it out in the client.js, which has the following code:

$( "#messageForm" ).submit( function() {
var nameVal = $( ); <-------- don't know what to put in here :S
var msg = $( "#messageInput" ).val();

socket.emit( 'message', { name: nameVal, message: msg } );

$.ajax({
url: "../ajax/insertMessage.php",
type: "POST",
data: { name: nameVal, message: msg },
success: function(data) {

}
});

return false;
});

socket.on( 'message', function( data ) {
var actualContent = $( "#messages" ).html();
var newMsgContent = 'Name: ' + data.name + ' Message:' + data.message;
var content = actualContent + newMsgContent;

$( "#messages" ).html( content );
});


My form:

<form class="input-group" id="messageForm">
<input type="text" id="messageInput" placeholder="Type message..." class="form-control" />
<span class="input-group-btn">
<input type="submit" class="btn btn-primary btn-flat" value="Send"></input>
</span>
</form>


I would appreciate any help! Thanks

Answer Source

i imagine you have something like this $_SESSION['username'] .

optional 1: put in the hidden input <input id="nameInput" value="<?php echo $_SESSION['username'];?>" type="hidden" /> then var nameVal = $('#nameInput').val();

optional 2: direct write in jquery script var nameVal = <?php echo $_SESSION['username'];?>;

update for optional 2: if you have separate javascript file. you can do this:

<script>
var nameVal= <?php echo $_SESSION['username'];?>; //do this rigth before you call js script that will process this var.
</script>
<script src="client.js"></script>

thats basically like include or require in PHP

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download