Protheine Protheine - 1 month ago 8
jQuery Question

Jquery post response not available

I'm new to javascript, and this problem may be trivial but I need help.
My goal is to send a post to a python server based on tornado.

In the following function :

var machin = $.post( '/room/testroom', function( data ) {
truc = data;
return truc;


I never get back the content of
truc
.
This variable has an url inside it who will be used to create a new Websocket connection.

When I do
console.dir(machin);
I see the wanted
responseText
with the wanted url in the console, but I'm not able to get it outside of the console.

The variable data itself inside the function has my wanted data, as if I do :
alert(data)

I see an alert box with the wanted url.

Feel free to ask me for details as I may not be entirely clear.

Server side, my python code is this one:

def post(self, RoomName):
print 'je poste'
db = connect(host=config.SQLSERVER, user=config.SQLUSER, passwd=config.SQLPASS, db=config.SQLDB)
cursor = db.cursor()
uri = self.request.uri
url = uri.split('/')
RoomName = url[2]
sql = 'SELECT RoomID FROM abcd_un WHERE RoomName = %s', [RoomName]
cursor.execute(*sql)
RoomID = cursor.fetchone()
print 'RoomID', type(RoomID)
RoomID = str(RoomID[0])
RoomID = RoomID.decode()
fullurl = 'ws://' + self.request.host + '/socket/' + RoomID

#print uri
db.close()
wsurl = {
'url': fullurl,
}
wsurl_encoded = tornado.escape.json_encode(wsurl)
self.write(wsurl_encoded)

Answer

Try:

var machin = function (){
     $.post( '/room/testroom', function( data ) {
     truc = JSON.parse(data);
     return truc;
}

Now call the function:

var response = machin();