JSP not calling ajax function - java

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

Related

Ajax how can I refresh a drop down after call servlet

I have the following jsp
<c:forEach items="${vlocomotoras}" var="vl" varStatus="i">
<select class="regimenFrenoLocomotora" id="regimenFrenoLocomotora" name="regimenFrenoLocomotora" onchange="calcularDocumentoTren();">
  <option value="P" ${"P" == v1.regimenFrenoLocomotoras ? 'selected="selected"' : ''}>P</option>
  <option value="G" ${"G" == v1.regimenFrenoLocomotoras ? 'selected="selected"' : ''}>G</option>
</select>
</c:forEach>
I have the following ajax post to a servlet
$.ajax({
type: "POST",
url: "/copernico/SrvRenfeSituacion",
data: {
"arrayLocomotora[]" : arrayLocomotora,
todo:todo,
fecha:fecha,
tren:tren
},
error:function(){
console.log("ERROR");
},
success:function(responseText){
alert('responseText ');
alert(responseText);
alert("Success");
}
});
This is the servlet
req.setAttribute("vlocomotoras", locomotoras);
Now I want to refresh the drop down with the new values of vlocomotoras. How can I do this?
Have your servlet return a json array with the data you need. See this question for doing that.
(In the ajax call, set dataType="json" for the call to expect a json object as response)
Once you get the json object in the ajax response, you can replace the OPTION tags inside the SELECT using jQuery (empty() and appendTo()).

How to send data from one jsp to another jsp and display data using ajax

I'm very new to ajax and jquery. I have a problem when using jsp and ajax to send data.
I know how to display result (Here I use a table) in the same page using ajax.
Now I want to click a button in the first jsp (the click button uses ajax to call servlet controller so as to get data from database, and then converting the data to json format), then show the result in the second jsp, but I was stuck how to do it.
Here's the code:
test.jsp
<body>
<input type='button' value='Show' id='ShowButton' />
</body>
<script type='text/javascript'>
$(document).ready(function() {
$("#ShowButton").click(function(event) {
$.ajax({
type : "POST",
url : "controller.view",
dataType : "json",
success : function(data) {
$.each(data, function (index, element) {
var showContent = '';
showContent += '<tr><td>' + element.cpId + '</td>
<td>' + element.cpName + '</td><td>'
+ element.createDate + '</td><td>' +
element.enable + '</td></tr>';
$("#content tbody").append(showContent);
});
}
});
});
});
</script>
test2.jsp
<body>
<div >
<table id='content'>
<thead>
<tr>
<th>ID</th>
<th>Content Provider Name</th>
<th>Create Date</th>
<th>Enable</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
Thanks.
//inside button click
$.ajax({
url: 'SaveData',
method: 'POST',
data: {
fname: $('#fname').val(),
sname: $('#sname').val(),
age: $('#age').val(),
address: $('#address').val(),
email: $('#email').val(),
gender: $('.gender:checked').val(),
phone: $('#phone').val(),
password: $('#password').val()
},
success: function (data) {
data = JSON.parse(data);
if (data.responce == 1)
alert("Success");
else
alert("Error");
},
error: function (error) {
console.log(error);
}
});

jQuery doesn't work in FF or IE but works fine in Chrome

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!

JSP form values passed to a servlet

I have a form in JSP in the following manner :
<form id="provision-field" method="post" action="${pageContext.request.contextPath}/myServlet">
<fieldset>
<ol class="fields">
<li>
<label for="field1">field1</label>
<input type="text" id="field1" "
value="<%= field1 %>"
/>
<span class="description">
<span class="optional">Optional</span>
</span>
</li>
</ol>
</fieldset>
<div class="actions">
<button type="submit" name="Submit">
Submit form
</button>
Cancel
</div>
</form>
I have a js snippet on click of the submit button does the following
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: field,
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
When I just use the form element (ie take out the js code) , I can reach my servlet but none of my form parameters are passed . when I try using the js code , the ajax request does not work . could someone point to me how this should be correctly done .
The servlet code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Inside the post function");
logger.info(request.getParameter("data");
}
var field = document.getElementById("field1").value;
$.ajax({
url: '${pageContext.request.contextPath}/myServlet'
type: 'POST',
data: {
data :field
},
dataType: "html",
success: function(html) {
alert("Success");
},
error: function(error){
alert("ERROR");
}
});
Inside servelt following code in doPost method :
Assuming that you have primary knowledge of HttpServlet...
request.getParameter("data");
I am sharing small Ajax with Servlet tutorial , which may help you for further problem... Download Link- AJAX Servlet Tutorial
data: { field1:field1Value } send like this
and then access request.getParameter("field1"); in servlet
As form submission method is post method="post", you need to make sure you are fetching request values in doPost(request, response) method

Getting Response Text From Ajax Call

I am trying to get the response from an Ajax call into a html label. I am using a tomcat server. Ia m able to see the description returned form the server however how do i get the responses into the lable text. Under is what i have tried:
Jquery
function GetDescription(Id){
$.ajax({
type:'GET',
url:'getDescription.htm',
data:{dId:Id},
dataType: 'json',
success: function (data) {
$('.TypeDesc').text = data.responseText;
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var typeId = document.getElementsByClassName("TypeId")[i].value;
GetDescription(typeId);
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
});
html
</head>
<body>
<div id ="content">
<c:forEach items="${object}" var="i">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${i.fName} ${i.lName}
<input type="hidden" id="photo" value="${i.photo}" class="photos"/>
<input type="hidden" id="Number" value="${i.Number}" />
<input type="text" class="TypeId" value="${i.citizenTypeId}"/>
<label class="TypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>
The problem is that you're telling jQuery you're expecting JSON:
dataType: 'json',
...and so it's (trying to) parse the response as JSON and pass you an object, but then you're trying to use it like a raw XHR object.
If you want the text, remove the dataType or change it to dataType: 'text', and then use data which will be a string.
Your other problem is that text is a function, not a property, so you need to call it.
So:
dataType: 'text',
success: function (data) {
$('.TypeDesc').text(data);
}
Please add this to the parameters of the ajax call
success: function(data) {
$('.TypeDesc').each(function(){
$(this).text(data);
});
}
You need to give the lable a unique ID like id="TypeDesc{i}" or something different.
So you can refer to it something like this:
$('#TypeDesc{i}').text = data.responseText;

Categories