IbrahimAsad
IbrahimAsad

Reputation: 516

How to send request parameter array to servlet using jQuery $.ajax?

I would like to send JavaScript array to servlet using jQuery $.ajax.

var json=[1,2,3,4];
$.ajax({
            url:"myUrl",
            type:"POST",
            dataType:'json',
            success:function(data){
                // codes....
            },
            data:json

        });

When I use

request.getParameter("json");
request.getParameterValues("json");

It returns null.

How can I access the values?

Upvotes: 18

Views: 35623

Answers (4)

Shubham Gupta
Shubham Gupta

Reputation: 61

Try using below script -

 jQuery.ajax({
                    url : "your API",
                    type : "POST",
                    dataType:'json',
                    data: JSON.stringify({ jsonData: data }),
                    contentType: "application/json",
                    success : function(response) {
    //do the needful.
    },
                    error : function(jqXHR, textStatus,
                            errorThrown) {
                        var x = 1;
                        closeLoader();  
                    }
                });

handle the request in the controller as below -

@RequestMapping(value="your url", method = RequestMethod.POST)
public Map<String, Object> verifyRefundRequested(@RequestBody String data) throws UnsupportedEncodingException{
        Map<String, Object> responseMap = null;
        Gson g = new Gson();
        responseMap = g.fromJson(data, Map.class);
        List<String> s = (List<String>) responseMap.get("jsonData");
//iterate list and process 
// return map
        }

Upvotes: 0

Raunak Agarwal
Raunak Agarwal

Reputation: 7238

Send array as value of JS object so you end up as {json:[1,2,3,4]}.

var json=[1,2,3,4];
$.ajax({
    url:"myUrl",
    type:"POST",
    dataType:'json',
    data: {json:json},
    success:function(data){
        // codes....
    },
});

In servlet, you need to suffix the request parameter name with [].

String[] myJsonData = request.getParameterValues("json[]");

jQuery appends them in order to be friendly towards weak typed languages like PHP.

Upvotes: 36

user1171884
user1171884

Reputation:

You need to post your javascript data object like this..

http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John", time: "2pm" },
   function(data) {
     alert("Data Loaded: " + data);
   });

Upvotes: -1

DWolf
DWolf

Reputation: 725

You have to convert your array to a JSON type so instead of [] it needs to read

 var array = [ 1, 2, 3, 4 ];

to do this you need to call

 var json = JSON.stringify(array)

then you can pass it into your ajax call

 $.ajax({ url:"myUrl",
          type:"POST",
          data: json,
          dataType:'json',
          success:function(data){
             // codes....
          }})

Upvotes: 0

Related Questions