1

I've seen a lot of posts about how to pass arrays via ajax in jquery. This is not exactly about those questions. Is the following reasonable behaviour or am I doing something wrong?

I have some simple jquery ...

var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
    url: url,
    data: {
        ids: changedIds
    },
    dataType: "json",
    traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
    window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
    console.log("Submit Fail: ");
});

The changedIds array will end up with 0-N integers in it. I check the .length before the POST so a zero length array is not sent. My question is about what happens when there is only ONE value.

It appears that having a single value array treats the "array" like a plain variable. The HTTP request lists the data as:

ids=123

The target of this ajax call is a .Net ActionResult method that wants an array value. It pouts and throws an exception if it is handed what looks like a plain variable.

I have started checking the array .length and if it is 1 then pushing in a known dummy value so that there are two values for the array. This seems to work -- but is this correct behaviour? Is this the best work-around?

2
  • Is your service expecting JSON in the request body? Commented Jan 20, 2017 at 17:20
  • Don't know really. I'm pretty new to the .NET game. It is an ActionResult method. Commented Jan 20, 2017 at 17:27

1 Answer 1

1

Try serializing your data parameter using JSON.stringify and specifying a contentType of application/json as follows:

var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
    url: url,
    data: JSON.stringify({
        ids: changedIds
    }),
    contentType: "application/json",
    dataType: "json",
    traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
    window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
    console.log("Submit Fail: ");
});

That should convert the JavaScript object into valid JSON and tell the server the type of data that you are sending.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that was it. I had tried the stringify but not in that way. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.