Cyril N.
Cyril N.

Reputation: 39889

Play Framework and jQuery Ajax request with data as Array

I am sending an Array of values through Ajax via jQuery with a Play Framework backend, and I'm in front of a problem.

Here's an example :

$.ajax ({
    'type':     'POST',
    'url':          '/url',
    'timeout':  5000,
    'data':     {'ids': [0, 1, 2, 3]},
    'dataType': 'json',
    'success':  function (oData) {
        // Process ...
    }
});

But in Play!, if I do a params.get("ids");, I got an empty value, and if I do a params.getAll("ids"); also.

I know where the problem is, jQuery send the data as : ids[]=0&ids[]=1&ids[]=2&ids[]=3 but Play! Framework expect array data to be sent as ids=0&ids=1&ids=2&ids=3

Is there a proper way to send the data properly (or get the data as an array in my controller) ?

So far, I managed to make it works simply but creating the request as a String manually in javascript.

Thanks for your help.

Upvotes: 3

Views: 3537

Answers (4)

det0
det0

Reputation: 281

Just add traditional: true to your jQuery.ajax request and the Array will be sent as ids=0&ids=1&ids=2&ids=3

$.ajax ({
    traditional: true,
    type:        'POST',
    url:         '/url',
    timeout:     5000,
    data:        {'ids': [0, 1, 2, 3]},
    dataType:    'json',
    success:     function (oData) {
        // Process ...
    }
});

Upvotes: 0

Md Samiul Alim Sakib
Md Samiul Alim Sakib

Reputation: 1114

This solution worked for me. Give it a try,

// Sending request
var params = {
    myArray: [1, 2, 3, 4]
};
var url = '@controllers.routes.AppController.jquery()';
$.post(url, params, function (data) {
    // Process response here
});

// Receiving request
Map<String, String[]> params = request().body().asFormUrlEncoded();
Logger.debug("Params : " + params.size());
for (Map.Entry<String, String[]> param : params.entrySet()) {
    Logger.debug(param.getKey() + " = " + param.getValue()[0]);
}

Upvotes: 1

PrimosK
PrimosK

Reputation: 13918

One method (leaving your JavaScript code intact) is just declaring your controller method like this:

public static void myMethod(@As("ids[]:")List<Long> ids) {
    System.out.println(ids.get(0));
}

.. the output is what you expect:

[0, 1, 2, 3]

Upvotes: 4

marchaos
marchaos

Reputation: 3444

I'm not sure if there's an easier way, but you could just send a string and decode that using GSON, i.e:

$.ajax ({
    'type':     'POST',
    'url':          '/url',
    'timeout':  5000,
    'data':     {'ids': '[0, 1, 2, 3]'},
    'dataType': 'json',
    'success':  function (oData) {
        // Process ...
    }
});

Within your controller, you can convert the string into an array:

// data would be "[0, 1, 2, 3]"
int[] intArray = gson.fromJson(data, int[].class);

Upvotes: 1

Related Questions