0

I'm having trouble sending the form via ajax. In addition to the fields populated by the user, I need to send an array of objects together.

AJAX POST:

submitHandler: function (form) {
                    $.ajax({
                        url: urlPost,
                        type: "POST",
                        dataType: "json",
                        data: $(form).serialize() + JSON.stringify(myArray),
                        success: function (resposta) {
                           alert('success');
                        }
                    });
                }

If I send only $(form).serialize() I can, but with the array not.

ARRAY:

myArray = [{name: 'a', node: 1}, {name: 'b', node: 12}, ...];
Leomar de Souza
  • 677
  • 10
  • 23

3 Answers3

0

Change your data: $(form).serialize() + JSON.stringify(myArray) to data: $(form).serialize() + "&arr=" + JSON.stringify(myArray). For Further help refer to https://stackoverflow.com/a/10398820/4518930

Adil Liaqat
  • 229
  • 3
  • 11
  • Unfortunately, it did not work even though the string was created. It happens that upon arriving at my Action, the array is null. Even though you have renamed *arr* to the name of the object that Action expects to receive :( – Leomar de Souza Jul 03 '19 at 01:44
  • I was able to solve it differently as I posted my answer. Thank you for the tips :) – Leomar de Souza Jul 03 '19 at 02:42
0

.serialize() + Some JSON String doesn't make sense.

According to the docs:

https://api.jquery.com/serialize/

The .serialize() method creates a text string in standard URL-encoded notation.

So you're really taking a string like foo=bar&goat=baz and then adding a JSON string to like. Which makes no sense.

I think you'd be better off serializing the form yourself into a JSON object. Adding another key for your array and then dumping that object to JSON via JSON.stringify and that string is your request data.

Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
0

After the tip of Cody Caughlan, I created an object that adds all the properties of the form and the array itself. The code looks like this:

var dataForm = {};
$($(form).serializeArray()).each(function(index, obj){
    dataForm[obj.name] = obj.value;
});
dataForm["MyArray"] = myArray;

And ajax: post: dataForm.

Leomar de Souza
  • 677
  • 10
  • 23