call the java method using ajax on button click - java

I have a button in blank.jsp (lets say).
<input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment"
style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">
when button is clicked I need to call the java method callprocedure() using ajax.
function payment()
{
alert('Payment done successfully...');
........
// ajax method to call java method "callprocedure()"
........
}
I am new to ajax. how can we call the java method using ajax. Please help me soon.
Thanks in advance.

try to use this method..
$.ajax({
url: '/servlet/yourservlet',
success: function(result){
// when successfully return from your java
}, error: function(){
// when got error
}
});

I suppose your payment is in a servlet.
All you need is this
function payment(){
$.ajax({
type: "POST",
url: "yourServletURL",
success: function(data){
alert("Payment successful");
},
error: function (data){
alert("sorry payment failed");
}
});
}

remove the inline onclick from the submit
add an onsubmit handler to the form
cancel the submission
I strongly recommend jQuery to do this especially when you have Ajax involved
I assume here the servlet function is in the form tag. If not, exchange this.action with your servlet name
$(function() {
$("#formID").on("submit",function(e) { // pass the event
e.preventDefault(); // cancel submission
$.post(this.action,$(this).serialize(),function(data) {
$("#resultID").html(data); // show result in something with id="resultID"
// if the servlet does not produce any response, then you can show message
// $("#resultID").html("Payment succeeded");
});
});
});

Related

Page content loaded with ajax - events firing multiple times

So I am loading my page using ajax, and everything is working fine using below
$( document ).ready(function() {
menuLoad('auction');
});
function menuLoad(page){
$.ajax({
type: 'post',
url: '/content/'+page+'/'+page+'.php',
async : false,
success: function (response) {
location.hash = page;
$("#contentLoad").html(response);
}
})
};
however if i try loading the same page multiple times, all buttons click events will fire multiple times.. I understand that every time I am loading the content, I am re-assigning a new event to the button while it already have one which cause each event to fire when a user click on it.. but how to fix this?
inside page content, the button will be something like below
<input type="button" value='New Sold' id='soldaddbtn' >
$( document ).on("click", "#soldaddbtn", function(){
$.ajax({
type: "POST",
url: "/content/sold/loadSoldAdd.php",
dataType: 'html',
success: function(response){
bootbox.dialog({message: response});
}
});
})
define a global variable and check for its existence.
if(!soldaddbtnClickEventisAdded) { // check if the variable is defined file is already loaded
$( document ).on("click", "#soldaddbtn", function(){
$.ajax({
type: "POST",
url: "/content/sold/loadSoldAdd.php",
dataType: 'html',
success: function(response){
bootbox.dialog({message: response});
}
});
});
}
var soldaddbtnClickEventisAdded = true; // add a global variable
I didn't understand your problem completely but try using following code:
As on() will bind the click event, so there might be the case that event is bounded multiple times. So unbind the click event then bind it again.
$("#soldaddbtn").off("click").on("click", function(){});
its javascript not java, you need event to fire once, the replace
$( document ).on("click", "#soldaddbtn", function(){
with
$("#soldaddbtn").on("click", function(){

Project Name getting appended to Output writer

Trying to display a value from database without refreshing the webpage using JQuery and Ajax was successful in displaying this however “Served at: /Project name” is getting appended to the value displayed
Script:
$(document).ready(function() {
$('#AESASJOBRUNOPTION').change(function() {
var AESASJOBRUNOPTION = $('#AESASJOBRUNOPTION').val();
$.ajax({
type:'POST',
url: "AESASJobCurrentOpenPeriod",
data: {AESASJOBRUNOPTION: AESASJOBRUNOPTION},
cache: false,
success: function(result) {
$("#result1").html(result);
$("#result1").html(result).slideDown('slow');
}
});
});
});
Servlet:
try{
if(ASCOGSRS.next()){
//System.out.println("Open Peiod is :"+ASCOGSRS.getString(1));
HttpSession OpenPeriodsession=request.getSession();
OpenPeriodsession.setAttribute("ASCOGSCurrentOpenPeriod", ASCOGSRS.getString(1));
PrintWriter out =response.getWriter();
String ASCOGSOpenPeriod=ASCOGSRS.getString(1);
out.print(" The Current Open Period is: "+ASCOGSOpenPeriod);
}
}
If your project is using JET Template from Eclipse, looks like the doPost method appends the extra Served at: <PATH>.
If JET Template is used, following are possible solutions:
Skip using JET Template in Eclipse Window -> Preferences -> Java EE
If Skipping JET Template is not possible and your AJAX request only retrieves the data, change the request type to GET instead of POST
If JET Template is not used, following is a solution at the Javascript level:
$(document).ready(function() {
$('#AESASJOBRUNOPTION').change(function() {
var AESASJOBRUNOPTION = $('#AESASJOBRUNOPTION').val();
$.ajax({
type:'POST',
url: "AESASJobCurrentOpenPeriod",
data: {AESASJOBRUNOPTION: AESASJOBRUNOPTION},
cache: false,
success: function(result) {
result_without_path = result.replace(/Served at:[\/a-zA-Z0-9]*/i,'');
$("#result1").html(result_without_path);
$("#result1").html(result_without_path).slideDown('slow');
}
});
});
});
You may also look for response writer in your servlets which may write the response it should be something like:
response.getWriter().append("Served at: ").append(request.getContextPath());
And then you can comment this line from your servlet.

Failed to replace the current page div content with another page div content in spring ajax call

i am newbie to spring.My requirement is to replace the current page content with another page content in spring ajax call.
Below is my code:
a1.jsp
<script>
$(document).ready(function(){
$("#my").click(function(){
$.ajax({
type : 'post',
url : 'CheckAjax',
success : function(data) {
console.log("success");
console.log(data);
$("#result").empty();
$("#result").html(data);
},
error : function() {
console.log("fail");
}
});
});
});
</script>
<div id="result">admin</div>
<input type="button" id="my"/>
ajaxcheck.jsp
<div id="result"><c:out value="${model}"/></div>
Spring Controller:
#RequestMapping(value="CheckAjax")
#ResponseBody
public ModelAndView myAjax(){
logger.info("i am executing");
return new ModelAndView("ajaxcheck","model","success");
}
The console displays
success
Object {view: null, model: Object, empty: false, viewName: "ajaxcheck", reference: true…}empty: falsemodel: ObjectmodelMap: Objectreference: trueview: nullviewName: "ajaxcheck"proto: Object
i already acheive this in my struts2 project.But i am struggle how to do this in spring?
Any help will be greatly appreciated!!!
Removing the #ResponseBody helps because there are some predefined return value handlers which work on the return type of the MVC controller
So when one return some Object the org.springframework.web.method.support.HandlerMethodReturnValueHandler interface comes into picture by identifying
the appropriate return type handler and then delegate the handling to proper handler.
Following return type are supported return type in Spring MVC 3.2.x and above.
ModelAndView or Model or Map or View
String or void
method annotated with #ResponseBody
HttpEntity or ResponseEntity or Callable or DeferredResult
These all are defined in following method
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#getDefaultReturnValueHandlers()
This is documented at http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-return-types

Need to implement struts2 form validation, which is a part of already loaded jsp

I am using struts2 and tiles framework.
in the default load I am loading baselayout.jsp. after tat I am not changing the url. it will remain constant, and the inner part will change using ajax query.
Now I need to implement struts form. Struts form action after success and failure trying to reload the complete page. I need to reload the form portion only not the entire page.
Alternative Question: Is it possible to trigger a function in javascript after a struts action is returned
Thanks in Advance
Krishna
I hope the following answer is help you.
$('#formEmp').submit(function(event) {
//Validate using jquery validator
if (!$('#formEmp').valid()) {
return false;
}
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
$inputs.prop("disabled", false);
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "saveEmp",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function(response, textStatus, jqXHR) {
// log a message to the console
alert("Saved Successfully");
initForm();
});
// callback handler that will be called on failure
request.fail(function(jqXHR, textStatus, errorThrown) {
// log the error to the console
alert(textStatus);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function() {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});

Redirect to login page onajax request

I am using jsp, jquery, and struts. I have a problem understanding the redirect to login page for ajax request. I tried to see request on browser on XHR tab and it gives me 302 status code in header. I am not able to comprehend how do I redirect.
My approach
The application has a function which checks if the user is signed in or not and has function to redirect to login url.
Else do some other processing.
How do I come back to same page after login? Is there any way? Also for redirecting on server side I am using Response.redirect(). When I debug the code and response comes on client side the error function in ajax function is executed not success function. Can someone explain how to catch response from server?
function buttonpress(param1,param2){
$.ajax({
type:"GET",
data:{
X:param1,
Y:param2,
},
url:"/application",
success:function(){
alert("success message");
}
error:function(){
alert("error message")
}
});
}
success:function(){
//current page URL
var ref = document.URL;
location.href = '/login/?ref=' + ref;
}
You can use variable "ref" to come back the same page
Note that when you use ajax to call server and receive a redirect response. The browser will not redirect, but will automatically retrieve the content at redirected location and your success function will end up being passed the content from the redirected location. For ajax request, you should not respond with a redirect if the user is not signed in, you should return a 401 Unauthorized instead and the browser will handle this in your callback. Here are the steps:
Check if the user is signed in or not
If the user is not signed in, check the headers for X-Requested-With: XMLHttpRequest (this indicates an ajax request)
If found and not authenticated, respond with 401 (for ajax requests) else respond with 302 (for not ajax requests).
And your ajax callback could check if there is a 401 response, set location.href to your login page. You could have something like returnUrl query string parameter in your login page, if there is you could set it to your current page to redirect to this page after login. Sample code on client side:
$.ajax({
type:"GET",
data:{
X:param1,
Y:param2,
},
url:"/application",
success:function()
{
alert("success message");
},
error:function()
{
alert("error message")
},
statusCode: {
401: function() {
location.href = '/login/?returnUrl=' + document.URL;
}
});
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#MsgDel').show(false);
jQuery("#MsgDel").dialog({
bgiframe: true, autoOpen: false, height: 150, modal: true, width: 300,
buttons: {
"OK": function () {
$(this).dialog("close");
--To Reload Page Again After Success Function
window.location.href = "DispatchInstructionList.aspx";
}
},
close: function () {
}
});
});
</script>
jQuery(document).ready(function () {
jQuery('#dialog').show(false);
jQuery('#MsgDel').show(false);
jQuery("#dialog").dialog({
bgiframe: true, autoOpen: false, height: 250, modal: true, width: 250,
buttons: {
"Delete": function () {
var txtValue = $("#<%=txtid.ClientID %>").val();
var txtrea = $("#<%=txtreason.ClientID %>").val();
if (txtrea == '') {
}
else {
Delete(txtValue, txtrea);
$(this).dialog("close");
}
},
"Cancel": function () {
$(this).dialog("close");
}
},
close: function () {
$('#txtreason').val("");
}
});
});
</script>

Categories

Resources