I have a button in jsp like this.
<input class="submit_button" type="submit" id="btnPay" name="btnPay" value="Payment"
style="position: absolute; left: 350px; top: 130px;" onclick="javascript:payment();">
The javascript function calls the java servlet and the servlet calls the function "callprocedure()" when the button is clicked.
<script>
function payment()
{
var req = $.ajax({
type: "POST",
url: '/context/Servlet',
success: function(result){
//when successfully return from your java
alert('Payment done successfully...');
}
}, error: function(){
// when got error
alert("sorry payment failed");
}
});
}
</script>
Now all works fine but my problem is to check the success or error in ajax. How can i check the success or error in ajax in my case.
Thanx in advance ...
You are doing that correctly, However you have syntax error in your code :
function payment() {
var req = $.ajax({
type: "POST",
url: '/context/Servlet',
success: function (result) {
// alert data returned by jsp
alert(result);
alert('Payment done successfully...');
},
error: function (jqXHR,textStatus,errorThrown) {
// when got error
alert("sorry payment failed :" + errorThrown);
}
});
}
you can use parameter passed to error callback to know the cause of error
More info
http://api.jquery.com/jQuery.ajax/
Another way to do it (not very efficient though):
Check the returned value from servlet.
$.post('Servlet',paramName:paramValue,...},function(result) {
if (result.substring(0,...)=='(expected result)'){ //success
}else{ //error
}
});
Hope it helps
Related
I have the form
<aui:form action="<%= editURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="name" />
<aui:input name="url" />
<aui:input name="address" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button name="cancel" value="Cancel"/>
</aui:button-row>
</aui:form>
and this piece of javascript code which is inserting into database twice I don't know why.
<aui:script use="aui-base,aui-form-validator,aui-io-request">
AUI().use('aui-base','aui-form-validator',function(A){
var rules = {
<portlet:namespace/>name: {
required: true
},
<portlet:namespace/>url: {
url: true
},
<portlet:namespace/>address: {
required: true
},
};
var fieldStrings = {
<portlet:namespace/>name: {
required: 'The Name field is required.'
},
<portlet:namespace/>address: {
required: 'The Address field is required.'
},
};
alert("validator");
new A.FormValidator({
boundingBox: '#<portlet:namespace/>fm',
fieldStrings: fieldStrings,
rules: rules,
showAllMessages:true,
on: {
validateField: function(event) {
},
validField: function(event) {
},
errorField: function(event) {
},
submitError: function(event) {
alert("submitError");
event.preventDefault(); //prevent form submit
},
submit: function(event) {
alert("Submit");
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
alert("inside success");// not getting this alert.
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
}
}
});
});
</aui:script>
However if I add the following piece of code, which is redundant because it is already present inside the submit block of above code and is not triggered any way because I do not have any save button in the form, then the value is inserted only once.
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
This code generates Uncaught TypeError: Cannot read property 'on' of null which I think is because there is no save button in the form. But adding this code, the value is inserted into database just once which is what I want but the logic is flawed. How can I get the results I want by just by using the first piece of code?
The insertion was happening twice. Once from the default form submit and other from the A.io.request. Adding this piece of code
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
resulted in the insertion only once. This code has obviously no relevance because there is no save button in the form. Hence there was Uncaught TypeError: Cannot read property 'on' of null which masked the flaw and prevented the form from being submitted twice.
Removing the above piece of code and preventing the default submit (by adding onSubmit="event.preventDefault(); in the form tag) resolves the issue.
I have a form in jsp:
<form id="emailForm" data-role="form">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter full name..">
<input type="submit" id="emailSubmit" name="emailSubmit" class="btn btn-default" value="submit">
</form>
I send the form to controller using AJAX:
$("#emailSubmit").click(function(e){
e.preventDefault(); //STOP default action
var postData = $("#emailForm").serializeArray();
$.ajax(
{
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I check if it has been submitted in Controller here:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String emailSubmit = request.getParameter("emailSubmit");
if(emailSubmit != null){
// continue
}}
Can someone please tell me why when it checks if form was submitted in the controller that it is null?
For forms the standard way is to catch the submit event instead of the click event of the button:
$("#emailForm").submit(function(e){
e.preventDefault();
var postData = $(this).serializeArray(); // or: $(this).serialize();
$.ajax({
type: "POST",
url : "HomeController",
data : postData,
success: function(data)
{
$("#emailResult").html("<p>Thank your for submitting</p>);
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#emailResult").html("<p>ss"+errorThrown+textStatus+jqXHR+"</p>");
}
});
});
I have tried several methods to be able to check the submit button isn't null and can't solve that issue. For now I have set a hidden input field in the form like so:
<input type="hidden" name="form" value="contactForm">
In controller I check for the form:
String form = request.getParameter("form");
if(form.equals("contactForm")){
// continue
}
Doing this enables me to know which form has been posted to the controller.
I have written an ajax function which will be called when someone selects a year from a dropdown. On selecting the year, the ajax will call a servlet based on passed URL and that servlet will set a value in properties file. However, the problem is, on selecting the year, my ajax block is not called
</tr>
<tr>
<td>Year</td>
<td>
<html:select property="yearId" >
<html:options collection=
"<%=GlobalValues.LIST_MODELYEAR%>"
property="id" labelProperty="value" />
</html:select>
(Required)
</td>
</tr>
<script>
$(document).ready(function()
{
$("#yearId").change(function()
{
var selectedValue = $(this).find(":selected").val();
$.ajax
({
url : "/ModelByYear.do?cID="+selectedValue+'',
});
});
});
</script>
Maybe you can check the url you build first before calling the AJAX?
$(document).ready(function()
{
$("#yearId").change(function()
{
var selectedValue = $(this).find(":selected").val();
window.location = "/ModelByYear.do?cID="+selectedValue;
});
});
Remove the / from your URL as given below and the , is not neccesory
$.ajax({
url : "ModelByYear.do?cID="+selectedValue
});
Try by using the below code
$.ajax({
type: "GET",
url: "ModelByYear.do",
data: {cID:selectedValue},
success: function(result){
alert('Result: ' + result);
},
error: function(err){
alert('Error: ' + e);
}
});
type is html request type you can use GET or POST
ModelByYear.do is URL in you case you must map this url-pattern in WEB.xml
While working on JSP's don't call jsp pages directly instead configure in WEB.xml as given here
I'm working on a project were I'm using REST to communicate with the db, it generates XML code, example of how it looks below.
<ns2:MultipleResponse xmlns:ns2="http://v1_0.model.service.mydomain.com">
<ns2:AttributeType>
<ID>1</ID>
<Version>0</Version>
<ns2:Name>Type of Address</ns2:Name>
<ns2:Definition>Definition for Type of Address</ns2:Definition>
<ns2:DataType>ShortText</ns2:DataType>
<ns2:MultipleSelect>false</ns2:MultipleSelect>
<ns2:AttributeGroupType>
<ID>1</ID>
<Version>0</Version>
<ns2:Name>Address</ns2:Name>
<ns2:Code>ADR</ns2:Code>
<ns2:Definition>Definition of Address</ns2:Definition>
</ns2:AttributeGroupType>
</ns2:AttributeType>
</ns2:MultipleResponse>
I call my REST from a web GUI which is in Spring MVC.
I use jQuery to populate one select dropdown from the choise of another select dropdown. This works in Chrome but not in FF or IE.
I use Firebug in FF and it gives me this error:
No elements were found with the selector: "AttributeType"
My jquery:
<script type="text/javascript">
$(document).ready(function() {
var html = '<option value>Välj</option>';
$('#serviceTypeAttributeGroup').change(function() {
$.ajax({
url: "http://server/project-web/services/rest/auth/v1_0/attributetypes/servicetypeattributegroup/" + $('#serviceTypeAttributeGroup').val(),
type: "GET",
contentType: 'application/xml; charset=utf-8',
dataType: "xml",
success: function(data) {
$(data).find("AttributeType").each(function() {
html = '';
var $attribute = $(this);
var id = $attribute.children("ID:first").text();
var name = $attribute.find("Name:first").text();
html += '<option value="' + id + '">' + name + '</option>';
$('#attributeType').html(html);
});
}
});
return false;
});
$('#attributeType').html(html);
});
I have tried to change "AttributeType" to "ns2:AttributeType", "ns2\\:AttributeType" and "ns2\:AttributeType" but that doesn't change the error message in FF and the code stops working in Chrome.
When I look at the XML in FF it just shows plain text, if that's of any help? In Chrome I see all the tags.
My select dropdowns:
<tr>
<th><label for="serviceTypeAttributeGroup"><s:message code="servicetypeattributegroup" />:</label></th>
<td><sf:select path="serviceTypeAttributeGroup.ID" id="serviceTypeAttributeGroup">
<sf:option value="0"> </sf:option>
<sf:options items="${listOfAttributeGroups}" itemLabel="attributeGroupType.name" itemValue="ID" />
</sf:select></td>
</tr>
<tr>
<th><label for="attributeType"><s:message code="attributetype" />:</label></th>
<td><sf:select path="attributeType.ID" id="attributeType">
<sf:option value="0"> </sf:option>
</sf:select></td>
</tr>
Is there anyone who has an idea of what is wrong? ANd how I correct it?
You should try to escape it like this:
$(data).find("ns2\\:AttributeType")
most probably this line causes the problem
url: "http://server/project-web/services/rest/auth/v1_0/attributetypes/servicetypeattributegroup/" + $('#serviceTypeAttributeGroup').val(),
you should try with relative path instead of giving the compete path to the server. Otherwise some browsers will block because of same origin policy
I changed my jQuery to
<script type="text/javascript">
$(document).ready(function() {
var html = '';
$('#serviceTypeAttributeGroup').change(function() {
html = '';
$.ajax({
url: '<c:url value="/mvc/serviceTypeAttribute/attributeTypes" />',
type: "GET",
data: "id=" + $('#serviceTypeAttributeGroup').val(),
dataType: 'json',
success: function(response) {
$(jQuery.parseJSON(JSON.stringify(response))).each(function() {
html += '<option value="' + this.id + '">' + this.name + '</option>';
$('#attributeType').html(html);
});
}
});
$('#attributeType').html(html);
});
return false;
});
</script>
and created a method in my controller and now it's working in both Chrome and FF.
Thank you for your input guys!
I have two JSP pages that must use the same javascript. The script attaches a function on an anchor. This function will call a database operation through the controller and service layer when user click on the anchors.
Both JSP pages has these anchors. Hence, it will be good if I can reuse this script in both pages. I am planning to create a JSP page that only has this script and include this pages in both jsp pages. Is this a good practice in re-using a javascript ? Are there any other better ways to do this ?
This is a snippet of the script:
$(document).ready(function(){
$('a[name*="like"]').click(function() {
var hrefName = $(this).attr("name");
var href = $(this);
$.ajax({
type: "POST",
url: "likeARecipe",
data: 'recipeId=' + $(this).attr("title") + '&operation=' + $(this).attr("name"),
success: function() {
if(hrefName == 'unlike')
{
$(href).attr("name","like");
$(href).text("like");
}else {
$(href).attr("name","unlike");
$(href).text("unlike");
}
}
});
return false;
});
});
UPDATE
I decided to put the script into a common.js script. I place this script under scripts/common.js.
I used tag to render the URL to this script.
<spring:url value="/resources/scripts/common.js" var="common_js" />
<script src="${common_js}" type="text/javascript"><jsp:text/></script>
I configure spring to read this script by specfying these resources in a context file:
<resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>
However, spring did not load the script in the JSP Pages. Any suggestion on a way to trouble shot the problem ?
UPDATE
I found a solution to this problem. I have to modify the script. I enclosed the script inside a function():
(function(){
alert("test");
$(document).ready(function(){
$('a[name*="like"]').click(function() {
var hrefName = $(this).attr("name");
var href = $(this);
$.ajax({
type: "POST",
url: "likeARecipe",
data: 'recipeId=' + $(this).attr("title") + '&operation=' + $(this).attr("name"),
success: function() {
if(hrefName == 'unlike')
{
$(href).attr("name","like");
$(href).text("like");
}else {
$(href).attr("name","unlike");
$(href).text("unlike");
}
}
});
return false;
});
});
})(jQuery);
Create an external .js file and reference it from both JSP pages, like this:
<script src="displaydate.js" type="text/javascript"></script>
Take a look here: http://www.javascriptkit.com/javatutors/external.shtml