Here is an HTML form input provided:
<input type="text" id="username" value="">
In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records:
$(function(){
//var socket = io.connect( 'http://'+window.location.hostname+':3000' );
$('#username').on('keyup',function(e){
var $this = $(this);
if(e.which === 13){
var name = $this.val();
socket.emit('new user', name, function(response){
if(response){
localStorage.setItem('username',name);
$this.val('');
$('#userinfo').hide();
$('#chat-body').fadeIn();
loadMessages(); //retrieve messages from Database
} else{
$('.validation').text('Username taken!').fadeIn();
}
});
}
});
function loadMessages(){
$.post('process.php',{method:'retrieve'},function(response){
$.each(JSON.parse(response),function(i,v){
$('.messages').append('<li><div class="msg-lhs"><span class="username">'+v.name+'</span> : <span class="msg">'+v.message+'</span></div><span data-livestamp="'+v.created_at+'" class="msg-rhs"></span></li>');
});
$('.messages').animate({scrollTop: $('.messages').prop("scrollHeight")}, 500);
});
}
});
The request now is to remove the keyup function() and instead pass the username in a hidden form. After that, retrieve the database records as soon as the page loads. Assistance on achieving this would be highly appreciated. Thank you!