Servlet POST request using AJAX.

Avatar

Avatar

jezwn

Avatar

jezwn

jezwn

08-10-2019

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());

    }

}

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

ArpitVarshney

MVP

Avatar

ArpitVarshney

MVP

ArpitVarshney
MVP

08-10-2019

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

Answers (4)

Answers (4)

Avatar

Avatar

ArpitVarshney

MVP

Avatar

ArpitVarshney

MVP

ArpitVarshney
MVP

08-10-2019

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

Avatar

ArpitVarshney

MVP

Avatar

ArpitVarshney

MVP

ArpitVarshney
MVP

09-10-2019

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

Avatar

Avatar

jezwn

Avatar

jezwn

jezwn

09-10-2019

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

Avatar

Avatar

jezwn

Avatar

jezwn

jezwn

08-10-2019

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.