4

I have array of ids like the follows:

var arr = [1, 23, 6];

I need to send this array to a server, parse it, and remove the ids from a mongoose db. For my backend I'm using nodejs express. So I need your advise how should I send the array by using jQuery and how should I parse it on a server.

Erik
  • 14,060
  • 49
  • 132
  • 218

2 Answers2

9

Basically a comment on @udidu's good answer, but I want markdown formatting so I'll post it as an answer. Here's some minor improvement suggestions:

  • Omit everything but the path from the url "/deleteIds" on the javascript side so it will work no matter how it is served.

  • You can send the array as a JSON string without an object wrapper

    $.ajax({
        url: '/deleteIds',
        type: 'DELETE',
        data: JSON.stringify([1, 2, 3]),
        contentType: "application/json",
        processData: false,
        success: function(data){
            console.log(data);
        }
    });
    
  • In the server, the array will be available as just req.body

  • As per REST conventions, this should be using the HTTP DELETE method (I've changed the jquery. You will also need to change the express code to do app.del instead of app.post).

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • it is replaced with {} to me :( – piggyback May 26 '14 at 11:46
  • 1
    Most important settings that made my use case work: - data: JSON.stringify(…) - processData: false - contentType: "application/json" – chitza Dec 17 '15 at 21:38
  • What you describe as 'sending the array without an object wrapper' is incorrect- you are sending a serialized version of the array as a string. You should leave that work to jQuery, or explain why you are overriding its serialization. – Dean Radcliffe Mar 10 '16 at 22:03
  • Because as I read the jquery `$.ajax` docs, the default serialization is not JSON: "By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false." – Peter Lyons Mar 10 '16 at 22:47
  • @nick, try JSON.parse(data) – Vladyslav Nikolaiev Aug 11 '16 at 13:14
4

Ok, follow this instructions and you are good:

first of all, lets create our node server, I'm using the Express module to define the HTTP server:

var fs = require('fs'),
    express = require('express'),
    app = express();


app.listen(8080);

app.use(express.bodyParser());

app.get('/', function(req, res){
    var html = fs.readFileSync('index.html');
    res.header("Content-Type", "text/html");
    res.send(html);
});

app.post('/deleteIds', function(req, res){
    console.log(req.body.arr[0]);
    res.json({ success: true });
});

The server '/' request returns an HTML page that will create an jQuery Ajax request, Here is the HTML file content:

<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script type="text/javascript">

        $.ajax({
            url: 'http://localhost:8080/deleteIds',
            type: 'POST',
            data: {
                arr: [ 1, 2, 3]
            },
            success: function(data){
                console.log(data);
            }
        });

    </script>

</head>
<body>
</body>
</html>

As you can see, the Ajax request in the html file sent as a POST request with an array as the data, The /deleteIds express path POST function in the server listens to that and takes the array using req.body.arr, note that I'm using app.use(express.bodyParser());, without this line we will not be able to get the body content from the POST request.

This is it.. I hope this is helping understand Node + Ajax requests using express, from this point you can run on the arr and do what you want with the data.

udidu
  • 8,269
  • 6
  • 48
  • 68