0

I have an array of input text

<input type="text" name="highlight" value="1"/>
<input type="text" name="highlight" value="2"/>

I used ajax and FormData() to submit it to the server.

var form = $(this);
var formData = new FormData(form[0]);
var target = form.attr('action');

$.ajax({
      url: target,
      type: 'post',
      data: formData,
      processData: false,
      contentType: false,
    })
    .done(function(data){
        console.log(data.message);
    });

**Expected Server result:**highlight=['1','2']
**Actual Server result:**highlight=2
Im using nodejs as server

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
Terinah14
  • 153
  • 1
  • 2
  • 13
  • In both the inputs you need to the name attribute to show that it is an array like this: `highlight[]` – MrMadsen Sep 30 '15 at 01:34
  • If the issue is on the node side check out this post: http://stackoverflow.com/questions/4586716/node-js-send-and-receive-array-as-get-post-using-querystring – MrMadsen Sep 30 '15 at 02:04

1 Answers1

1

You need to add brackets to your input name attributes highlight[]. This way the browser knows they are part of the same array and won't overwrite one with the other.

<input type="text" name="highlight[]" value="1"/>
<input type="text" name="highlight[]" value="2"/>
MrMadsen
  • 2,713
  • 3
  • 22
  • 31
  • I tried putting brackets but it will return undefined accessing highlight. It is working even if there is no bracket when I'm using serialize(). But for now I need to use FormData because I'm also uploading a file. – Terinah14 Sep 30 '15 at 01:41
  • On the server or the browser? – MrMadsen Sep 30 '15 at 01:42
  • In server. The result is highlight[]:2. It should be highlight:['1','2'] @MrMadsen – Terinah14 Sep 30 '15 at 01:47
  • Have you checked the post variables sent via the debugging tools in the browser? This will let you know if it is being sent as an array or not which I suspect it is being sent as an array and the error is actually on the node side. This post will tell you how to check the post variables: http://stackoverflow.com/questions/15603561/how-can-i-debug-a-http-post-in-chrome – MrMadsen Sep 30 '15 at 01:50
  • ------WebKitFormBoundaryGYnwRf2PWLWpdBtb Content-Disposition: form-data; name="highlight[]" 1 ------WebKitFormBoundaryGYnwRf2PWLWpdBtb Content-Disposition: form-data; name="highlight[]" 2 – Terinah14 Sep 30 '15 at 01:54
  • 1
    From that it looks like both values are being sent but node isn't receiving them correctly. You could try adding the index into the bracket `highlight[0]` and `highlight[1]`. If that still doesn't work then change it back to serialize and look at the post variables being sent and compare them to the ones you just commented - that way you'll know what node is expecting. – MrMadsen Sep 30 '15 at 01:59
  • Putting an index number to the highlight name help to solve the problem. but it is not an array anymore. It is now like an individual variable. Thanks – Terinah14 Sep 30 '15 at 23:15