GSDa
GSDa

Reputation: 193

Get session value using JQuery/Ajax

I'm a newbie in this, I'm trying to refresh a menu value (cart content) without reloading the whole page.

This is my issue : ${cartSession.getCartContent()} value in the alert check is Undefinied.

If it could help, In server side I'm using Spring.

$(document).ready(function(){
           var $form = $("#panierform");
           $form.submit(function(){
              $.post($(this).attr('action'), $(this).serialize(), function(response){

              },'json');
              alert("Ajouté avec succès !");
              refreshCartValue();
              return false;
           });

        });

        function refreshCartValue() {
            alert(${cartSession.getCartContent()});
            $("#cartValue").text("");
            $("#cartValue").text(${cartSession.getCartContent()});
        }

Upvotes: 0

Views: 10631

Answers (2)

GSDa
GSDa

Reputation: 193

Thank you for your response, very useful tutorial, here is my code it does work now :

$(document).ready(function(){
           var $form = $("#panierform");
           $form.submit(function(e){
              $.post($(this).attr('action'), $(this).serialize(), function(response){
                  alert("Ajouté avec succès !");
                  refreshCartValue(response);
              },'json');
              e.preventDefault();
              return false;
           }); 

        });



        function refreshCartValue(response) {
            $("#cartValue").text("");
            $("#cartValue").text(response);
        }

Be sure to add e.preventDefault(); what I missed before was the return value as ResponseBody from the controller :

@RequestMapping("pages/addToCart")
   public @ResponseBody String addToCart(HttpSession session, @RequestParam String produitId, @RequestParam Long quantite){

       //
       return String.valueOf(cart.getCartContent()); 
   }

Upvotes: 0

isah
isah

Reputation: 5341

 alert(${cartSession.getCartContent()});

You can't call a server side Java method from Javascript.

Javascript executes on the client browser, Java on the server.

What you can do is handle form posting VIA Ajax. Make a POST request to server, return the actual response(with success/failure flags) and do whatever you want with it via JQuery/Javscript:

Follow this simple example with Spring: http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/

Upvotes: 2

Related Questions