fancy
fancy

Reputation: 51393

How do I pass form data over a websocket? (socket.io)

<form name="input" action="">
    <input type="text" name="say" /> 
    <input type="submit" value="send" />
</form>

I want to send the data in this form to the server via web sockets, i'm using socket.io.

What is the best way to achieve this?

Upvotes: 7

Views: 10594

Answers (2)

HamzaO
HamzaO

Reputation: 37

you can try this

    function getFormData2Object(form){
    var un_array = form.serializeArray();
    var _array = {};
    $.map(un_array, function(n, i){
        if(n.name.indexOf('[') > -1 ){
            var array = n.name.match(/\[(.*?)\]/);
            var key = n.name.replace(array[1],"").replace('[',"").replace(']',"");
            if(!_array[key]){
                _array[key] = {};
            }
            _array[key][array[1]] = n['value'];
        }else{
            _array[n['name']] = n['value'];
        }
    });
    return _array;
}
socket.emit('blablabla', getFormData2Object( $("form") ) );

good luck :)

Upvotes: -3

onteria_
onteria_

Reputation: 70527

You'd need to use .serialize() on the form like so:

var formdata = $('form').serialize();

Then pass that over the websocket. On the node.js side, you can get a JS object back by using querystring.parse:

var querystring = require('querystring');
// Data is the data received from the client
var result = querystring.parse(data);

Upvotes: 13

Related Questions