2

RESOLVED! see solution at bottom of this post...I have been stuck on this problem for about 2 days now and it's starting to get to me. I am trying to POST a Json array to my node server (cross-domain) and insert it to a cloudant db. This question is more about just getting the json over in the correct format. Here is my client side json and ajax:

function stress(){
var start = new Date().getTime();
$.ajax({
    type: 'POST',
    url: 'url/',
    crossDomain: true,
    data: JSON.stringify(products),
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    success: function(responseData, textStatus, jqXHR) {
        var end = new Date().getTime();
        var millis = (end - start);
        var duration = (millis/1000);
        alert(responseData.msg +'Duration(seconds): ' + duration);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
    }
});
}

var products = [
{
    name: 'War Room Table',
    year: '2005',
    color: 'tan',
    country: 'USA',
    description: 'A Beautiful War Room table. Includes all 4 legs!',
    usaDollarPrice: 150
},
{
    name: 'Power Strip',
    year: '2000',
    color: 'white',
    country: 'USA',
    description: 'A very old power strip, may or may not protect against power surges.',
    usaDollarPrice: 16
}];

My Node.js server side:

exports.create = function(req, res) {
    var data = req.body;
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Content-Type', 'application/json');
    //var parsed = JSON.parse(data);
    var msg = {};
    for(product in data){
    db.insert(data[product], function (err, body, headers) {
        if (!err) {
            msg.msg = 'success!';
            console.log(JSON.stringify(msg);
        }

        else {
            msg.msg = 'Error on insert, maybe the item already exists: ' + err
            console.log(JSON.stringify(msg);
        }

    });

} }

I have tried a multitude of different things. What I basically want is a object on the server side that I can iterate through and insert to the cloudant database, each as a separate doc. I have tried many combinations of JSON.stringify and JSON.parse. using parse has given no luck as I get an error saying SyntaxError: Unexpected token o which I read that means it is already an object, but I cannot access data in any way ( data[0], data.name, data[0].name, nothing on the server side). I have also tried sending the json from the client side in different ways (in ajax - data: JSON.stringify({prod:products}) and still no luck.

Having the json on the server side (same as products above) inserts the docs in the correct order, the problem is when I sent that same json over a ajax post and to a cross-domain server. I cannot get that json out. Any idea or help would be very appreciated, thanks

Solution:

I ended up putting the object into another array and using that to be sent to the server. Here is the working ajax in the client side, notice the data:{data:products} that's what did it for me. Also below is the products json and also how to access it on the nodejs server side.

$.ajax({
    type: 'POST',
    url: 'url/',
    crossDomain: true,
    data: {data:products},
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded",
    success: function(responseData, textStatus, jqXHR) {
        var end = new Date().getTime();
        var millis = (end - start);
        var duration = (millis/1000);
        alert(responseData.msg +'Duration(seconds): ' + duration);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
    }
});

var products = [
{
    name: 'War Room Table',
    year: '2005',
    color: 'tan',
    country: 'USA',
    description: 'A Beautiful War Room table. Includes all 4 legs!',
    usaDollarPrice: 150
},
{
    name: 'Power Strip',
    year: '2000',
    color: 'white',
    country: 'USA',
    description: 'A very old power strip, may or may not protect against power surges.',
    usaDollarPrice: 16
}];

Here is how to access it on the server side. Keep in mind this is all for cross-domain Post, but should work otherwise.

exports.create = function(req, res) {
    var body = req.body;
    //body.data[0] will get you the first object in the json, in this case it will be the war room table. 
    //If you use console.log to see it make sure you JSON.stringify(body.data[0]) or else you wil see [Object] [Object]

Also very important to include this in your server/app.js The extended: true part is important. Example

app.use(bodyParser.urlencoded({ extended: true }));
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
  • 1
    Use: `contentType: "application/json; charset=utf-8"` – UltraInstinct Dec 11 '14 at 05:14
  • Hi Thrustmaster do you mean replace this part with application/json - application/x-www-form-urlencoded. I don't think the restful call will work without x-www-form-urlencoded – Andrew Lohr Dec 11 '14 at 05:39
  • Yes! BTW, a restful call has nothing to do with the encoding of the data you are sending, as much as it has got to do with the actual resource. I haven't worked with Node, but I am pretty sure that it is unable to decode the JSON data using percentile encoding mentioned in the Content-Type header. – UltraInstinct Dec 11 '14 at 06:36
  • Ohh, and additionally, I see that you are trying to do a cross domain request. I hope your Node server is set up for it. – UltraInstinct Dec 11 '14 at 06:41
  • I just got around trying your replacement of x-www-form-urlencoded and the POST would just fail right away :( and yea my node server is setup to accept cross domain requests that part is okay. – Andrew Lohr Dec 11 '14 at 18:51

2 Answers2

1

I am new to ajax. Please check if this helps. I think I had a similar problem which is solved now.

Please see the answer posted by me

How to send array of arrays as data in $.ajax()?

Community
  • 1
  • 1
Pragya Sharma
  • 94
  • 1
  • 2
  • 9
1

You are stringifying the json data before sending it to the node server, try only data:products You will also need the node module body-parser using it you will be able to access POSTed data through ajax, see this answer also

Community
  • 1
  • 1
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
  • Hey Thanks, after forming the json into an second array and also sending the data without stirngify solved my problem. – Andrew Lohr Dec 11 '14 at 20:05