M.Chaymae
M.Chaymae

Reputation: 307

how to pass a javascript object to a Java Servlet

I have a javascript object that i want to pass to a java Servlet, how can i perform this operation ? I have already tried few things but didnt work out.

Here is my code :

$.ajax({
    url: 'TestUrl',
    data: {
        object: myJavaScriptObject
    },
    type: 'GET'
});

and in the servlet (doGet method)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String result = request.getParameter("object");
    System.out.print(result);
}

but i just get null in the console.

I'm also interested on how to perform the opposite operation, pass a java object in the servlet to a JavaScript Object.

Thank you in advance.

Upvotes: 1

Views: 1261

Answers (2)

Umesh Kumar Sharma
Umesh Kumar Sharma

Reputation: 306

$.ajax({
                        url: 'TestUrl',
                        method: 'post',
                        data: {
                            object: myJavaScriptObject
                        },
                        success: function(data) {
                            if(data.success) {
                //process your data here
                }
                        }
                    });

List item

Upvotes: 0

Killer Death
Killer Death

Reputation: 459

Change GET to POST for sending data.

    $.ajax({
    url: 'TestUrl',
    dataType: 'json',
    data: {
        object: myJavaScriptObject
    },
    type: 'POST'
    });

Upvotes: 1

Related Questions