ajax call to do action when onclick checkbox in ofbiz - ajax

I want to use checkboxes with options say id1,id2.when i choose id1 a ajax will run through javascript and call the appropriate action and return the response.i dont want to reload the page.please post some freemarker, controller.xml, java codes to do this.

Based on my understanding of the question, the following script might be helpful you:
in ftl file itself/ in seperate js file you add the following script:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#id1").click(function(){
if(jQuery(this).is(":checked")) {
var reqUrl= "checkbox1_Url";
sendAjaxRequest(reqUrl);
}
});
jQuery("#id2").click(function(){
if(jQuery(this).is(":checked")) {
var reqUrl= "checkbox2_Url";
sendAjaxRequest(reqUrl);
}
});
});
function sendAjaxRequest(reqUrl){
jQuery.ajax({
url : reqUrl,
type : 'POST',
data : {'var1': 'val1', 'var2' : 'val2'}, //here you can pass the parameters to
//the request if any.
success : function(data){
//You handle the response here like displaying in required div etc.
},
error : function(errorData){
alert("Some error occurred while processing the request");
}
});
}
</script>
In freemarker,
<input type="checkbox" id="id1" name="checkbox1" />
<input type="checkbox" id="id2" name="checkbox2" />
In controller.xml:
<request uri="checkbox1_Url">
<!-- fire if any events are here -->
<response name="success" type="view" value="ViewName1" />
<response name="error" type="view" value="errorViewName" />
</request>
<request uri="checkbox2_Url">
<!-- fire if any events are here -->
<response name="success" type="view" value="ViewName2" />
<response name="error" type="view" value="errorViewName" />
</request>
<view-map name="ViewName1" type="screen" page="component://.../widget/screensFileName#screenName"/>
<view-map name="ViewName2" type="screen" page="component://.../widget/screensFileName#screenName"/>
You define two screens in widgets as specified in the above path(page="...." attribute of view-map tag).

jQuery(function() {
jQuery('input[type = checkbox]').bind('click',function() {
var categoryId ="";
if(jQuery(this).is(':checked')) {
categoryId = jQuery(this).val();
}
var reqUrl= "categoryurl";
sendAjaxRequest(reqUrl, categoryId);
});
});
function sendAjaxRequest(reqUrl, categoryId){
jQuery.ajax({
url : reqUrl, // Here the Url will have to return the all products related to
//passed category
type : 'POST',
data : {'categoryId': categoryId}, //here you can pass the parameters to
//the request if any.
success : function(data){
//You handle the response here display all products in a div etc.
},
error : function(errorData){
alert("Some error occurred while processing the request");
}
});
}
<input type="checkbox" id="id1" name="checkbox1" value="yandamuri_cat"/><label for="id1">YandaMuri</label>
<input type="checkbox" id="id2" name="checkbox2" value="chetanBhagat_cat"/><label for="id2">Chetan Bhagath</label>
In Controller.xml:
<request uri="categoryurl">
<!-- fire if any events are here -->
<response name="success" type="view" value="ViewName" />
<response name="error" type="view" value="errorViewName" />
</request>
<view-map name="ViewName" type="screen" page="component://.../widget/screensFileName#screenName"/>
Define a screen in appropriate location/path specified in above page attribute of viw-map tag.
Here, the screen may be without decorator, so that the response will come without decorator and so you can display them in the current page, without reloading. Entire page.
I guess this might help you.

Related

Why is my data being appended to my url after editing an item?

I'm building a simple recipe collections app, and I'm running into a really weird scenario where when I edit a recipe item, the new data gets appended to my localhost:3000/ url. For example my original recipe item data was:
"Title: test",
"Ingredients: test",
"Cooking Directions: test"
But then after I edited the data, the new data also appended to my localhost:3000/ url. data appended to localhost url screenshot. My goal is not append this data to my url and stay at localhost:3000. Thanks and any help would be appreciated.
Here is my put request code:
updateRecipe = (e) => {
console.log(this.props.uniqueID);
const recipe = {
title: this.state.title,
ingredients: this.state.ingredients,
summary: this.state.summary
}
const url = `http://localhost:5000/recipes/${this.props.uniqueID}`;
axios.put(url, recipe)
.then(res => this.setState({
recipes: [...this.state.recipes, res.data],
},
() => console.log('recipe edited: ', res.data)
));
}
<form className="form-container" onSubmit={this.updateRecipe}>
<TextField
style={inputStyle}
className="form-input-title"
type="text"
onChange={this.onChangeHandler}
name="title"
id="standard-basic"
label="Title"
value={this.state.title}
/>
<TextField
style={inputStyle}
className="form-input-ingredients"
type="text"
onChange={this.onChangeHandler}
name="ingredients"
id="standard-basic"
label="Ingredients"
value={this.state.ingredients}
/>
<TextField
id="outlined-multiline-static"
label="Directions"
multiline
rows={6}
variant="outlined"
onChange={this.onChangeHandler}
name="summary"
className="form-input-directions"
style={inputStyle}
value={this.state.summary}
/>
<Fab style={style} className="add-recipe-button" color="primary" aria-label="add" type="submit">
<AddIcon />
</Fab>
</form>
This is the default behaviour if you use onSubmit handler for form.If this is not what you are looking for dont use onSubmit handler on the form instead use onClick handler for the submit button to call for updateRecipe functionality.Then Url is not modified.

Play framework write Action with Ok(...) that doesn't load new page

Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps

How to embed web-service reponse within the portlet that called it?

Apologies for starting another thread but I kind of solved the issue of my first thread but now I run into a different issue.
Background:
I have a portlet which takes 3 Parameters (Temperature,FromUnit,ToUnit) and passes them on to an external WebService located here:
http://www.webservicex.net/ConvertTemperature.asmx/ConvertTemp
I did not want the portlet to actually redirect to the URL of the webService and the only way to do that appeared to be AJAX using jquery which I have done now.
However I also want the response of the webService to be embedded in the same portlet that I used to call it and that's where I am having issues.
This is what I got so far, here is my portlet page:
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<script src="http://localhost:8080/my-greeting-portlet/jquery.js"></script>
<script type="text/javascript" src="http://localhost:8080/my-greeting-portlet/js/script.js"></script>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects />
<%
PortletPreferences prefs = renderRequest.getPreferences();
String Temperature = (String)prefs.getValue("Temperature","Temperature");
PortletPreferences prefs2 = renderRequest.getPreferences();
String FromUnit = (String)prefs2.getValue("FromUnit", "FromUnit");
PortletPreferences prefs3 = renderRequest.getPreferences();
String ToUnit = (String)prefs3.getValue("ToUnit","ToUnit");
%>
<portlet:renderURL var="editGreetingURL">
<portlet:param name="jspPage" value="/edit.jsp" />
</portlet:renderURL>
<div id="contact_form">
<form name="callWebService" id="callWebService" action="">
<fieldset>
<label for="Temperature" id="Temperature_label">Temperature </label>
<input type="text" name="Temperature" id="Temperature" size="30" value="" class="text-input" />
<label class="error" for="Temperature" id="Temperature_error">This field is required.</label>
<br />
<label for="FromUnit" id="FromUnit_label">From unit </label>
<input type="text" name="FromUnit" id="FromUnit" size="30" value="" class="text-input" />
<label class="error" for="FromUnit" id="FromUnit_error">This field is required.</label>
<br />
<label for="ToUnit" id="ToUnit_label">To Unit </label>
<input type="text" name="ToUnit" id="ToUnit" size="30" value="" class="text-input" />
<label class="error" for="ToUnit" id="ToUnit_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="submit" />
</fieldset>
</form>
</div>
</body>
</html>
And here is the jquery code:
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
var dataString = $("#callWebService").serialize();
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.webservicex.net/ConvertTemperature.asmx/ConvertTemp",
data: $("#callWebService").serialize(),
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
$('.error').hide();
var Temperature = $("#Temperature").val();
if (Temperature == "") {
$("#Temperature_error").show();
$("#Temperature").focus();
return false;
}
var FromUnit = $("input#FromUnit").val();
if (FromUnit == "") {
$("label#FromUnit_error").show();
$("input#FromUnit").focus();
return false;
}
var ToUnit = $("input#ToUnit").val();
if (ToUnit == "") {
$("label#ToUnit_error").show();
$("input#ToUnit").focus();
return false;
}
});
});
Everything seems to be working, or at least I do not get errors but it seems that this part of the code is completely ignored:
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
When I press the "submit" button nothing happens. No redirection to the webservice URL (good) but also the custom message defined above does not show up (bad). The screen remains exactly as it is.
When I uncomment the "alert" in the jquery code and the parameters are definitely picked up correctly and I would assume that they are being passed to the webService URL but nothing else is happening.
Is this because the webservice URL returns a response that overwrites my message or something like that?
How can I get the webService response embedded into the portlet?
Again, many thanks for looking at this, it is much appreciated!
You ran into a Cross Domain Scripting problem.
Read this and this to resolve the problem

Spring.addElementDecoration for dijit.form.filteringselect fails in IE

I am using Spring Roo to create a page that makes ajax call and populates a section of the page with the search form from the Ajax call. This is all done by using standard Roo tags and Javascript libraries. The form that is returned by Ajax is simple, just one select list.
<jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields"
xmlns:form="urn:jsptagdir:/WEB-INF/tags/form"
xmlns:springform="http://www.springframework.org/tags/form"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:spring="http://www.springframework.org/tags" version="2.0">
<div>
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<form:search
id="fc_domain_profile_combination"
modelAttribute="combination" path="/profiles/search/combinations"
z="e2lXrqKKD2CS7Zjefas2ZXPW4xYNM=">
<field:select field="searchProcessingCenter" renderempty="true" disabled="true"
id="c_profile_combofilter_processingcenter"
items="${proccenters}" path="/profiles"
itemLabel="name" itemValue="id"/>
</form:search>
<input type="hidden" id="blockSubmitHd" value="false" />
</div>
This code works fine in Firefox and Google Chrome but fails in IE with "Unknown error". The problem is happens in the Ajax method included in Roo:
function callXhrGet(contentId, ajaxUrl){
var _targetNode = dojo.byId(contentId);
var xhrArgs = {
url: ajaxUrl,
preventCache: true,
handleAs:"text",
load: function(data) {
dojo.html.set(_targetNode,data,{parseContent:true});
dojo.forEach(dojo.query("script", _targetNode),function(node){
dojo.eval(node.innerHTML);
});
dojo.parser.parse(_targetNode);
},
error: function(error) {
_targetNode.innerHTML = "An unexpected error occurred: " + error;
}
};
dojo.xhrGet(xhrArgs);
}
The dojo.eval(node.innerHTML); fails when tries to process following line:
Spring.addDecoration(new Spring.ElementDecoration({elementId : '_searchProcessingCenter_id', widgetType: 'dijit.form.FilteringSelect', widgetAttrs : {hasDownArrow : true, required : false, invalidMessage: 'Please enter valid Role Type' }}));
The interesting part is that when the list is empty it works fine, other dijit.form.tags work fine as well. Any advice and feedback how to resolve this issue?

Struts2 AJAX validation doesn't stay on page

I've been trying for a few days now to make Struts2 AJAX validation work but I can't solve one last problem. I'm using the struts2jquery plugin to asynchronously submit my form:
<div id="result"></div>
<s:form action="RegisterUser" theme="xhtml" method="post">
<s:textfield key="firstname" label="First name" size="35"
required="true" />
<s:textfield key="lastname" label="Last name" size="35"
required="true" />
<s:textfield key="address" label="Address" size="35"
required="true" />
<s:textfield key="phone" label="Phone number" size="35" />
<s:textfield key="username" label="Username" size="35"
required="true" />
<s:password key="password" label="Password" size="35"
required="true" />
<s:textfield key="email" label="E-mail address" size="35"
required="true" />
<sj:submit key="Inregistrare" targets="result" align="right"
button="true" validate="true" onSuccessTopics="notifyRegistration" />
</s:form>
I've included the required scripts:
<script type="text/javascript" src="./js/registerScript.js"></script>
<!-- This files are needed for AJAX Validation of XHTML Forms -->
<script src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/struts/xhtml/validation.js"
type="text/javascript"></script>
and the tag:
<sj:head jqueryui="true" />
The onSuccess handler:
$(document).ready(function(){
$.subscribe('notifyRegistration', function(event,data) {
var registrationStatus = event.originalEvent.data.registrationStatus;
if(registrationStatus == 'SUCCESS'){
alert('Contul dumneavoastra a fost creat cu success!');
window.location.href = "./index.html";
} else {
alert('Contul dumneavoastra nu a putut fi creat. Va rugam incercati din nou.');
}
});
});
My configuration looks like this:
<action name="RegisterUser" class="actions.Register" method="execute">
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="input">/pages/Register.jsp</result>
<result type="json"/>
</action>
And the execute method of my action class:
public String execute() throws Exception {
if (isInvalid(getUsername()) || isInvalid(getPassword())
|| isInvalid(getEmail())) {
registrationStatus = REGISTRATION_ERROR;
}
if (registerUser()) {
registrationStatus = REGISTRATION_SUCCESS;
return SUCCESS;
}else {
registrationStatus = REGISTRATION_ERROR;
}
return SUCCESS;
}
The registerUser() method makes the actual insert into the database. The validation XML is called Register-Validation.xml.
The validation works fine - if some fields are not filled in, it shows the error labels without refreshing the page. My problem is that even is the action returns SUCCESS or ERROR, the browser displays the JSON that it sent back on another page, ../Register.action. I have no idea why it doesn't enter my onSuccess handler. I've successfully used AJAX on other forms, the only difference here is that I use the validation xml and the jsonValidationWorkflowStack interceptor. Why is this happening and how can I avoid being redirected? Why doesn't the request reach the onSuccess handler?
Do you have getters for registrationStatus in your Action ?
I would put an alert(event.originalEvent.data.registrationStatus); in your notifyRegistration callback function, just to see what is its value.
By the way, it seems that you have mixed
Struts2-jQuery Plugin AJAX Form Validation with Struts2 XHTML Theme
with
Struts2-jQuery Plugin: Remote Link that handle an JSON Result with an onSuccessTopic
AFAIK (but I've never used this specific kind of validation), the validation should not be handled in execute(), but in validate() or through XML, or with Annotations.
The example in Struts2-jQuery Plugin showcase uses Annotations, but you can easily transform it in XML and try the showcase.
You would have no need to use the javascript function nor the onSuccessTopic at all, following the example.
You can run it in the showcase too, under Forms -> Forms with Validation (but stick to the documentation for the code, because the code in the showcase seems to miss some pieces... for example the validation against "test" password).

Resources