Server side, I use below function (used as espressjs middleware)
function objCreation(req, res, next){
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
// Set params in request
obj = {};
obj.label = fields.label;
// Check if picture is provided
if(files.image){
// Move file to correct dir
var fs = require("fs");
var folder = '/var/images/';
var src = files.image.path;
var filename = files.image.name;
var target = folder + filename;
obj.filename = filename;
req.obj = obj;
fs.rename(src, target, function (status) {
next();
});
} else {
obj.filename = 'nofile';
req.obj = obj;
next();
}
}
});
}
Basically, it receives the fields of a form submitted. This function uses “connect-form” node.js module.
Client side, I use an input text:
<input id="new_obj" type="text" placeholder="New"/>
and a callback triggered when return is hit on this input:
// Add callback for object creation
$('#new_obj').keypress(function(e){
if (e.which == 13){
createObj();
}
});
The createObj function is the following one:
function createObj(){
$.ajax({
url: "/object/create/",
type: "POST",
data: { label : "label" },
success: function(obj) {
console.log(obj);
},
error: function(jqXHR,status,errorThrown) {
alert(jqXHR.responseText + '-' + status + '-' + errorThrown);
}
});
}
I do not manage to have this last part sending a form in the correct format so it is processed with the server method. I do not want to change the server side as it is already used by some other clients (iOS client sending form with ASIFormDataRequest).
I’m currently having a look at ajaxForm jQuery plugin to see if this could help.
I managed to have this fixed by using the last version of expressjs that does not use connect-form anymore (deprecated) but uses formidable instead.