javascript - Sending an array in POST body -
im trying send array node/mongodb server via , ajax post request. body contains other variables. here client side js code:
function setupform(){ $("#add").submit(function(event) { event.preventdefault(); var name = $("#name").val(); var logo = $("#logo").val(); var phone = $("#phone").val(); var email = $("#email").val(); var address = $("#address").val(); var postcode = $("#postcode").val(); var openinghours = $("#openinghours").val(); var loc = [44, 44]; $.ajax({ type: "post", url: "http://localhost:3000/services", data: "name=" + name + "&logo=" + logo + "&phone=" + phone + "&email=" + email + "&address=" + address + "&postcode="+ postcode +"&openinghours=" + openinghours + "&loc=" + loc, success: function(){alert('success');} }); }); }
and here the server side code:
exports.addwine = function(req, res) { var wine = req.body; console.log('adding wine: ' + json.stringify(wine)); db.collection('services', function(err, collection) { collection.insert(wine, {safe:true}, function(err, result) { if (err) { res.send({'error':'an error has occurred'}); } else { console.log('success: ' + json.stringify(result[0])); res.send(result[0]); } }); }); }
it adds database in format. in array:
"postcode" : "ugh", "openinghours" : "fhgfh", "loc" : "44,44"
given data using, advise sending data in post requests' body. retain datatypes (array, bools, etcs) json.
$.post("http://localhost:3000/services", { name: $("#name").val(), loc: [44, 44] ...etc }, function(){alert('success');} );
backend should work fine without alterations. might need add body-parser middleware stack. body-parser middleware transform body javascript object can push right database.
Comments
Post a Comment