0

The following JavaScript

new Ajax.Request('/orders/check_first_last/A15Z2W2', 
{asynchronous:true, evalScripts:true, 
parameters:{first:$('input_initial').value, 
last:$('input_final').value, 
order_quantity:$('input_quantity').value}});

triggers an Ajax call to the checkFirstLast method in the OrderController:

@Controller
@RequestMapping("/orders")
public OrderController {

   @RequestMapping("/check_first_last/{code}")
   @ResponseBody
   public String checkFirstLast(@PathVariable String code, 
        @RequestParam int first, 
        @RequestParam int last, 
        @RequestParam("order_quantity") int orderQuantity)  {
       Integer newResult = new Integer(last - first);
       return newResult.toString();
  }
}

If I want to write the newResult String from the checkFirstLast method into the result_text HTML element on the page that sends the Ajax request, replacing the value set by the initialResult JSTL variable:

<h2 id="result_text"><c:out value="${initialResult}"/></h2>

what change would I need to make to the controller method above (checkFirstLast), now that I have already included the Jackson JSON library in my project?

2 Answers 2

1

the flow in ajax is:

  1. send request with javascript to server
  2. process request on server
  3. sent response back to client
  4. process response with javascript and update the page

The 4th step is missing in the code you provide.

It seems to me you are using the prototype javascript framework, is this correct? If you look at the documentation for ajax requests and the ajax options you will see you can specify callback function when the requests was handled with success, or when a failure occured.

Change your javascript to:

new Ajax.Request(
    '/orders/check_first_last/A15Z2W2', 
    {
        asynchronous:true,
        evalScripts:true, 
        parameters:
        {
            first:$('input_initial').value, 
            last:$('input_final').value, 
            order_quantity:$('input_quantity').value
        },
        onSuccess: function(transport) 
        {
             $('result_text').update(transport.responseText);
        }
    }
);

and let me know what it gives.

1

This is an abstract controller that I wrote to handle Ajax. This actually is from the Struts example on DispatchAction.

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        AjaxResponse ajaxResponse = null;
        String parameter = "command";

        try {
            String methodName = request.getParameter(parameter);
            Method method = getMethod(methodName);

            ajaxResponse = invokeMethod(request, response, method);         
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(e.getLocalizedMessage());
            ajaxResponse = toXmlException(e);
        }

        if (ajaxResponse != null) {
            //Finally
            response.setContentType(ajaxResponse.getContentType());
            response.setHeader("Cache-Control", "no-cache");
            OutputStream out = response.getOutputStream();
            out.write(ajaxResponse.getResponseText().getBytes());
            out.flush();
        }

        return null;
    }

As you can see, A javascript is sent to the server, which is then dispatched by the DispatcherServlet to the controller. The controller then invokes the correct method call and returns a response through response.getOutputStream().write(....).

The controller then must return a null so that the DispatcherServlet does nothing in return.

In my case, AjaxResponse is an interface and the response can be either XmlAjaxResponse or JsonAjaxResponse.

The java client then handles the response returned from the server (in this case, controller).

You need to add in a response to your side. Hope this helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.