Expand my Community achievements bar.

SOLVED

Servlet POST request using AJAX.

Avatar

Level 6

Sending servlet POST request using AJAX causes page refresh and even if the form fields are set to required it is sending the request anyhow and the response is received. The page gets refreshed on clicking OK on the alert window. Also the data is send via url without any encoding (http://localhost:4502/content/auki/test/offerlandingpage.html?name=Candle&description=hello ). How to work around these!

The HTML

<form >

  Offer Name:<br>

  <input type="text" name="name" required><br>

  Description:<br>

  <input type="text" name="description">

  <br>

  <input type="submit" id="submit" value="Submit">

</form>

The JS

$(document).ready(function() {

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

$.ajax({

type: "POST",

url: "/bin/test2",

data: $('form').serialize(),

processData: false,

success: function(resp) {

alert("Name: " + resp.name + " Description: " + resp.desc);

}

});

});

});

The Servlet

package com.auki.core.servlets;

import java.io.IOException;

import javax.servlet.Servlet;

import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;

import org.apache.sling.api.SlingHttpServletResponse;

import org.apache.sling.api.servlets.HttpConstants;

import org.apache.sling.api.servlets.SlingAllMethodsServlet;

import org.json.JSONException;

import org.json.JSONObject;

import org.osgi.framework.Constants;

import org.osgi.service.component.annotations.Component;

@Component(service=Servlet.class,

property={

        Constants.SERVICE_DESCRIPTION + "=Test Post Servlet",

        "sling.servlet.methods=" + HttpConstants.METHOD_POST,

        "sling.servlet.paths="+ "/bin/test2",

        "sling.servlet.extensions=" + "json"

})

public class TestPostServlet extends SlingAllMethodsServlet  {

private static final long serialVersionUID = 1L;

    @Override

    protected void doPost(final SlingHttpServletRequest req,

            final SlingHttpServletResponse resp) throws ServletException, IOException {

  

  

    String name = req.getParameter("name");

    String description = req.getParameter("description");

  

    JSONObject obj = new JSONObject();

    try {

          obj.put("name", name);

          obj.put("desc", description);

         } catch (JSONException e) {    

          // TODO Auto-generated catch block

          e.printStackTrace();

         }

    resp.setContentType("application/json");

    resp.setCharacterEncoding("utf-8");

    resp.getWriter().write(obj.toString());

    }

}

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi,

Please update your JS as below(changes highlighted in yellow) to prevent form submission.

1842905_pastedImage_0.png

Alternatively, you can change the form type as button instead of submit to solve this issue.

Regards,

Arpit Varshney

View solution in original post

5 Replies

Avatar

Correct answer by
Community Advisor

Hi,

Please update your JS as below(changes highlighted in yellow) to prevent form submission.

1842905_pastedImage_0.png

Alternatively, you can change the form type as button instead of submit to solve this issue.

Regards,

Arpit Varshney

Avatar

Level 6

The page refresh has now been resolved adding the preventDefault(). But the form is submitted anyways, tried with changing input type to button and its still the same.

Avatar

Community Advisor

Hi,

You can write js code to validate the input field on form submit or easiest way to use Jquery form validation plugin if you want to add validation on input field without page refresh.

Good Links:

https://stackoverflow.com/questions/15060292/a-simple-jquery-form-validation-script

https://jqueryvalidation.org/

Avatar

Level 6

Okay cool. What about data sending over URL plain as visible!

Avatar

Community Advisor

Hey,

Please check your jquery version.

You should use type if you're using versions of jQuery prior to 1.9.0

Otherwise try using method parameter instead of type as it seems like it is making a GET call instead of post.(You can verify using browser network calls)

Reference:

https://api.jquery.com/jquery.ajax/

https://stackoverflow.com/questions/43543174/what-is-the-diff-between-type-and-method-in-ajax

Regards,

Arpit Varshney