Reputation: 649
I have a client.js and a server.js, in server.js i'm connected to mysql table, and sending queries from client to server. as i get the queries results into the socket.on('event',function(queryResult{...})) in client.js i can't use the result outside that scope (inside client.js but outside that scope)
all connections are done locally with a port at localhost.
index.html:
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="includes/client.js"></script>
<body>
<div id="getQueryStr"></div>
</body>
server.js:
var io = require('socket.io').listen(3000);
var mysql = require('mysql');
.
.
.
io.sockets.on('newQuery', function(newQuery){
MySql_Connection.query(newQuery)
.on('result', function(queryResultsData){
queryResultsArr.push(queryResultsData);
})
.on('end', function(){
socket.emit('query results', queryResultsArr);
});
});
client.js:
$(document).ready(function() {
var socket = io.connect('http://localhost:3000');
var html='';
var tempStr='';
$('input#centerSearchInp').bind('keypress', function(e){
if(e.keyCode==13){
socket.on('query results', function(queryResult){
html = queryResult[0].firstName;
$('#getQueryStr').html(html); //////OK!
tempStr = html;
});
alert(tempStr); //////////NOT OK!
}
}
});
I have tried using innerText and all kind of stuff but no metter what i'm doing, i just not able to use this data outside that scope.
Upvotes: 0
Views: 487
Reputation: 3011
You have to write a function with callback for the alert,
$(document).ready(function() {
var socket = io.connect('http://localhost:3000');
var html='';
var tempStr='';
$('input#centerSearchInp').bind('keypress', function(e){
if(e.keyCode==13){
socket.on('query results', function(queryResult){
getTempStr(queryResult, function(tempStr){
alert(tempStr);
});
});
}
}
});
function getTempStr(queryResult, callback){
html = queryResult[0].firstName;
$('#getQueryStr').html(html);
callback(html);
}
Upvotes: 1
Reputation: 1398
I guess the alert displays an empty box. Where are you importing the 'server.js' file ?
you may want to try not having 'var' as declaration of tempStr.
Upvotes: 0