How i can load chat-history with array, Socket.IO - javascript

I have chat on Socket.IO, MySQL, PHP. Everything is working good, but i need download and diplay messages history when you update the page.
php code:
<script>var USER = {"id":"<?php echo $_SESSION['steamid']?>","login":"<?php echo $_SESSION['personaname']?>","image":"<?php echo $_SESSION['avatarmedium']?>","hash":"<?php echo md5($_SESSION['steamid']) ?>"};</script>
js site code:
var messageTpl = _.template($("#chat-message").html());
function sendMessage(text) {
socket.emit('message', {user: USER, message: text});
}
var lastUser = null;
function addMessage(data, checkLast) {
var a = $("#chatScroll")[0];
var isScrollDown = (a.offsetHeight + a.scrollTop) == a.scrollHeight;
if (checkLast && lastUser && lastUser.id == data.user.id) {
$('.chatMessage').last().find('.body').append('<br/>' + _.escape(data.message))
}
else {
console.log(data);
data.user.url = 'http://steamcommunity.com/profiles/' + data.user.id;
data.user.image = 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + _.escape(data.user.image).replace('_medium', '');
var html = messageTpl(data);
$('#messages').append(html);
if ($('.chatMessage').length > 100) {
$('.chatMessage').eq(0).remove();
}
}
lastUser = data.user;
if (isScrollDown) a.scrollTop = a.scrollHeight;
$("#chatScroll").perfectScrollbar();
}
socket.on('online', function(data) {
$('#online').text(data.online);
});
socket.on('chat-message', function(data) {
addMessage(data, true);
});
socket.on('chat-history', _.once(function(data) {
$("#chatScroll").perfectScrollbar();
if (data) _.each(data, addMessage);
}));
function addMessage works good, but with socket.on('chat-history') i got error
Uncaught TypeError: Cannot read property 'id' of undefined
js server code:
connection.query('SELECT * FROM cs_chat ORDER BY id DESC LIMIT 50', function(error, rows) {
if(!error) {
var user = [];
rows.forEach(function (data) {
user.push(data);
});
console.log(user);
socket.emit('chat-history', {user: JSON.stringify(user)});
} else {
console.log(error.message);
}
});
when you refresh the page - all last messages lost
console.log server js rows.forEach below.
[{"id":668,"message_text":"3qwe","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:15.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":667,"message_text":"12312","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":666,"message_text":"213123","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":665,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":664,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":663,"message_text":"g","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":662,"message_text":"gdf","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":661,"message_text":"df","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"}]

Related

Angularjs problem: cannot resolve variable, but variable exists

I'm doing a project for University where I have a login for a website and I have to implement some operations. My issue is to maintain user session when a user is logged; so, if I open the website in a new tab, I want to be logged with the account of the main tab.
This is my angularjs code for the loginController:
mainAngularModule
.controller('LoginCtrl', ['$scope', '$state', 'AuthFactory',
function ($scope, $state, AuthFactory) {
let ctrl = this;
ctrl.authRequest = {username: 'admin', password: 'password'};
ctrl.doLogin = doLoginFn;
ctrl.authMessage = '';
//check if user already logged
let logSession = localStorage.getItem(("authinfo"));
if(logSession == null){
console.log("logSession null");
}
if(logSession == undefined){
console.log("isundefined");
}
if(logSession != null){
console.log("not null");
console.log("usern: " + logSession.username);
//console.log("authinfo authorities: " + logSession.authorities)
AuthFactory.setJWTAuthInfo(logSession);
$state.go("dashboard.home");
}
console.log("login authinfo: " + localStorage.getItem("authinfo"));
let sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key === 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
} else if (event.key === 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
}
function doLoginFn() {
console.log("doLoginFn");
var requiresLogin = $state.jwtToken;
console.log("requireLogin: " + requiresLogin);
AuthFactory.sendLogin(ctrl.authRequest, successCB, errorCB);
function successCB(response) {
let authInfo = response.data;
console.log("data = " + response.data.all);
let header = response.headers();
authInfo.jwtToken = header['authorization'];
console.log("authInfo", authInfo);
// AuthFactory.user.username = authInfo.username;
// AuthFactory.user.role = authInfo.role;
let debugJWT = true;
//if (debugJWT) {
if (true) {
console.log(authInfo);
console.log("username: " + authInfo.username);
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("jwtToken: " + authInfo.jwtToken);
console.log("userType: " + authInfo.userRole);
console.log("ended.");
}
AuthFactory.setJWTAuthInfo(authInfo);
//console.log("authinfoo1234: " + authInfo);
// localStorage.setItem("authinfo",authInfo);
console.log("authorities: " + authInfo.authorities);
$state.go("dashboard.home");
}
function errorCB(response) {
let error = response.data;
if (error && error.status === 401) {
ctrl.authMessage = error.message;
}
else {
console.error(response);
ctrl.authMessage = 'No response from server';
}
}
}
}
]);
I have a very strange problem: I'm using Intellj, and it tells me in lines
console.log("roles: " + JSON.stringify(authInfo.authorities));
console.log("userType: " + authInfo.userRole);
but if I comment lines with localStorage.setItem and localStorage.getItem, console prints on output correct userType and userRole; if I add those lines, console prints out this message:
TypeError
​
columnNumber: 17
​
fileName: "http://localhost:63342/ISSSR_frontend/app/scripts/service/AuthFactory.js"
​
lineNumber: 59
​
message: "authInfo.authorities is undefined"
I really don't understand, why it says me that it cannot resolve variable, but it can print out it?
Unfortunately I could not deploy your code would you please prepare codepen or flickr.
Some points that I can mention is below:
instead of use console.log("username: " + authInfo.username); use : console.log('username : ',authInfo.username)
Instead of JSON.stringify(authInfo.authorities) use : angular.toJson(authInfo.authorities,true)
Also console.log(response) to see what it returns.

Ionic app working on browser but not on device?

i have designed app using ionic and angularjs. Earlier the app was working fine but now i have changed the api ....the app working on browser but not on device...its functionalities not working on device..
before changed the api(app working on device):
var CONSTANTS = "http://ip_address/api/";
var api = CONSTANTS+'api.php?method=register' + '&user_registration=';
$http.post(api, {username : username,email : useremail,pwd : userpassword}).success(function(response) {
if( response[0].status == 1){
$cordovaToast.showShortBottom('Successfully Registered').then(function(success) {
// success
}, function (error) {
// error
});
document.getElementById('user_email').innerHTML = "";
document.getElementById('user_email').innerHTML = "";
document.getElementById('user_email').innerHTML = "";
$state.go('auth.login');
}else if( response[0].status == 0){
$cordovaToast.showLongBottom('Existing User or Invalid Data').then(function(success) {
// success
}, function (error) {
// error
});
}else {
//console.log('Error');
}
}, function(err) {
// console.log(err);
});
after changing the api in the code(app not working on device):
var CONSTANTS = "https://www.test.com/api/";
var api = CONSTANTS+'api.php?method=register' + '&user_registration=';
$http.post(...)... // Same as above

Upload multiple photos in batch to Facebook using Javascript SDK

I can upload single photos via URL to Facebook, but I'm having trouble doing it using batch. I'm getting the (#324) Requires Upload File uncaught exception. I'm ensuring the user is logged in and when I look at the batch payload (batchJson) it looks okay.
To be clear, if I remove all the batch-related setup code and in the FB.api call replace "batch" : batchJson with a single "url": photoUrl the code works.
Here's my code. TIA for any insight on my error:
var message = $("#message-fb").val();
var batchItems = [];
var photoUrl = "";
$(".photo-selected").each(function () {
photoUrl = $(this).data('content');
item = {};
item['method'] = 'POST';
item['relative_url'] = 'me/photos';
item['url'] = encodeURI(photoUrl);
item['caption'] = message;
batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);
alert(batchJson);
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// Already logged in and authorized
FB.api(
"/",
"POST",
{
"batch": batchJson
},
function (response) {
if (response && !response.error) {
/* successful upload */
alert('Photos uploaded to Facebook (nl) - ' + JSON.stringify(response));
}
if (response && response.error) {
/* Provide error info during testing */
alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
}
});
} else {
// Need to login and authorize
FB.login(function () {
FB.api(
"/",
"POST",
{
'batch': batchJson
},
function (response) {
if (response && !response.error) {
/* successful upload */
alert('Photos uploaded to Facebook - ' + JSON.stringify(response));
}
if (response && response.error) {
/* Provide error info during testing */
alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
}
});
}, { scope: 'publish_actions' });
}
});
EDIT: Here are the relevant changes using #CBroe's answer:
$(".photo-selected").each(function () {
var photoUrl = $(this).data('content');
var item = {};
item['method'] = 'POST';
item['relative_url'] = 'me/photos';
var itemUrl = encodeURI(photoUrl);
var itemCaption = encodeURIComponent(message);
item['body'] = "caption=" + itemCaption + "&url=" + itemUrl;
batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);
You are sending url and caption parameters on the same “level” as the method and relative_url – they need to be put inside a body property however. And the content of that field has to be encoded the same way an actual POST request via a form would be encoded (so like a URL query string, param1=value1&param2=value2).

Placing the errors in its respective div

Here i am getting my Error Messages from a separate page and i am displaying it in a a div called #stage_error
$('#stage_error').html(error_string);
So, the errors will be displayed like this
The bus no field is required.
The comp id field is required.
The total seats field is required.
But what i want is to display the errors in its respective div's
i.e., the Bus no should be displayed near the div <div id='busno'> like this.
How can i do that ?
Json :
{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
Update :
Script for request and showing error :
<script>
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
});
$('#stage_error').html(error_string);
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
</script>
Laravel Controller :
public function managebusregister()
{
$BusNo = Input::get('BusNo');
$CompID = Input::get('CompID');
$TotalSeats = Input::get('TotalSeats');
$data = Input::except(array('_token')) ;
$rule = array(
'BusNo' => 'required|unique:company_bus',
'CompID' => 'required',
'TotalSeats' => 'required|max:50'
) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return json_encode($validator->messages()); //php encoded value
}
else
{
DB::insert('insert into company_bus (BusNo, CompID, TotalSeats) values (?, ?, ?)',
array($BusNo, $CompID, $TotalSeats));
return '';
}
}
Html Code :
<div id="stage_error" style="color:red;font-size:15px"></div>
<div id="stage_success" style="color:green;font-size:20px"></div>
and beyond that i have each field input boxes,
<input type="text" id="BusNo" name="BusNo"/>
<input type="text" id="CompID" name="CompID"/>
How can i throw error messages near the respective fields
Below is the approach: Observe I've added spans with error after text boxes.
CSS
<style>
.error { color:red; font-size:15px; }
</style>
Html
<input type="text" id="BusNo" name="BusNo" /><span class="error"></span>
<input type="text" id="CompID" name="CompID" /><span class="error"></span>
JavaScript I did some changes as per the jQuery standard, it should work well, if you're not interested then you can ignore all the changes but can take only below mentioned if logic block.
The error display added in if (!data) {...}
$(function () {
$(document).on("click", "#driver", function (event) {
var BusNo = $("#BusNo").val(),
CompID = $("#CompID").val(),
TotalSeats = $("#TotalSeats").val(),
_token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
}).done(function (data) {
$("span.error").empty();//All previous error messages cleared here.
if (!data) {
var obj = JSON.parse(data);
//obj = {"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
$.each(obj, function (entry) {
var targetSelector='';
if (entry == "busno") {
targetSelector = "#BusNo";
}
if (entry == "Comp Id") {
targetSelector = "#CompID";
}
if(targetSelector) //Here we're setting error message for respective field
$(targetSelector).next("span.error").html(obj[entry]);
});
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
you can try like this:
var json = JSON.parse('{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}');
// alert(json['busno']);
$("#busno").html(json.busno);// like this for others also.
change here:
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
if(entry == 'busno'){
$("#busno").html(obj[entry]);// like this for others also.
}
if(entry == 'Comp Id'){
$("#compid").html(obj[entry]);// like this for others also.
}
});
$('#stage_error').html(error_string);

Check if DB exists and dropping DB in SQLlite IOS

I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i &lt result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.

Categories

Resources