1 Reply Latest reply on Dec 24, 2012 3:41 PM by nfilotto

    Ajax call to REST service

    drwho

      HI,

      I created a portlet to call a REST service . Below is the code for the javascript:

       

      <body>

      <form id="myform">

      <input type="text" id="keyword"/>

      <div id="target">Save Data</div>

      </form>

      <script type="text/javascript">

      // dummy submit function

      jQuery(document).ready(function () {

      $("#target").click(function() {

      var rootURL = "rest/request";

      alert ('value is '+$('#keyword').val() );

      $.ajax({

      type: 'PUT',

      contentType: 'application/json',

      url: rootURL + '/address' ,

      // dataType: "json",

      data: formToJSON(),

      success: function(data, textStatus, jqXHR){

      alert('Address updated successfully. Status: '+textStatus); },

      error: function(jqXHR, textStatus, errorThrown){

      alert('updateAddress error: ' + textStatus); }

      });

      function formToJSON() {

      return JSON.stringify({

      "address": $('#keyword').val()

      }); }

      });

      });

      </script>

      </body>

       

       

      Here it the service I am trying to call:

       

      @Path("/address/{address}/")

          @PUT

          @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})

          @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })

          public Response putAddress(@PathParam("address") String address) throws Exception {

             requestObject.setAddress(address);

            return Response.ok("Address is  " + requestObject.getAddress() + " !").build();

          }

       

       

      After I made the Ajax call which returns a success I go the following exception :

       

      2012-11-20 10:26:50,172 ERROR [portal:UIPortletLifecycle] (http-127.0.0.1-8080-4) Portlet render threw an exception

      org.exoplatform.services.portletcontainer.PortletContainerException: java.lang.NullPointerException

       

      However the Ajax call was not successful when I queried my Java object.

      Please see attached server log.

      What could be causing the problem? How do I make it work?

      Gordon

       

       

       

       

        • 1. Re: Ajax call to REST service
          nfilotto

          The first problem I see is the URL var rootURL = "rest/request"; should be actually var rootURL = "/rest/request";

           

          Did you try to test your rest component using curl before using jquery just to make sure that your rest component works as expected?

           

          I personnaly tested with:

           

          HTML block in my portlet:

           

          <form id="myform">
                    Name of the stock <input type="text" id="name" />
                    Price of the stock <input type="text" id="price" />
                    <div id="target">Save Data</div>
          </form>
          
          <script type='text/javascript'>
          function formToJSON() {
                    return JSON.stringify({"name": $('#name').val(), "price": $('#price').val()});
          }
          jQuery(document).ready(function () {
                    $("#target").click(function() {
                              var rootURL = "/rest/Stock";
                              $.ajax(
                                        {
                                                  type: 'PUT',
                                                  contentType: 'application/json',
                                                  url: rootURL + '/put' ,
                                                  data: formToJSON(),
                                                  success: function(data, textStatus, jqXHR){ alert('Stock updated successfully. Status: '+textStatus); },
                                                  error: function(jqXHR, textStatus, errorThrown){ alert('update Stock error: ' + textStatus); }
                                        }
                              );
                    });
          });
          </script>
          

          My Rest Component:

           

          @Path("/Stock")
          public class MyStockManager implements ResourceContainer
          {
          
             private final Map<String, Stock> stocks = new HashMap<String, Stock>();
          
             @Consumes(MediaType.APPLICATION_JSON)
             @Produces(MediaType.APPLICATION_JSON)
             @PUT
             @Path("/put")
             public Stock put(Stock stock)
             {
                System.out.println("Trying to put the stock " + stock.getName());
                stocks.put(stock.getName(), stock);
                return stock;
             }
          }
          

           

          My Stock Bean

           

          public class Stock
          {
          
             private String name;
          
             private long price;
          
             public Stock() {};
          
             public Stock(String name, long price)
             {
                this.name = name;
                this.price = price;
             }
          
             public String getName()
             {
                return name;
             }
          
             public void setName(String name)
             {
                this.name = name;
             }
          
             public long getPrice()
             {
                return price;
             }
          
             public void setPrice(long price)
             {
                this.price = price;
             }
          }