I have two textfield A , B : i want to do something like when i enter something in textfield A,this value will be use it in some action and result will be displayed in textfield B without clicking the submit button using ajax.
how can i do it please ? note that i am a using struts2
Most of the information has already been provided by #alexanderb and i believe that Jquery is good way to go, now lets come to the second half of your question about using AJAX in your code. there are few ways you can send results from your action class.
Return JSON from your action class and use above code.
Use stream result type in your S2 code and place the data in the textfield.
Still i believe JSON with Jquery is good way to go which not only provides you the feasibility to easily extend functionality in future but also provide a clean way.Struts2 provides a plugin which can convert the data being send from your action class to JSON and all you will be left to parse the JSON data in your UI to fill the text-box.For details how to work with JSON in s2 refer to JSON plugin for detail
S2-json-plugin
With JSON plugin your flow will be
Call your Action class on specific event in text box.
Configure your action to return JSON data using S2-JSon plugin.
Action will return JSON to the Jquery code.
Parse the JSON data and fill the text box with the value
It should be easy. Suppose you have action that takes value as string and return some string back, availble on '/app/service' url.
You can create such code for that:
$(function() {
$('#text_1').on('keyup', function() {
var value = $(this).val();
$.post('/app/service', JSON.stringify(value), function (r) {
$('text_1').text(r);
});
});
});
Related
Good evening,
I have a form on a JSP page that's connected to a servlet, that form has some dynamic parts using JavaScript like adding a row to a table or adding a text field based on the selected option on a select element, Actually my problem is that I have some validations on the servlet-side, so when I go to servlet to check the (National ID) for example if there's any problem or any violations to my validation I force to get back to the form using :
if (dbm.MatchIdNumber(Candidate.getRegNumber(), Candidate.getNationalID()) == false) {
out.println("<script>\n"
+ " alert('Your National Id does not match your Registration Number');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
What happens is when I get back to the form I lose all the JavaScript changes, Which's very important.
I've been reading for a while that using ajax might be the optimal solution for me, but here is my questions:
Is there a way to call a java method from JavaScript or JQuery before getting to servlet without using ajax !?!
Is there a way to get back from the servlet to the jsp page with the ability to keep all the JavaScript Chages !?
If not !!, How to use ajax in my case ?!
Thank you so much
No. JavaScript runs on the user's browser and your Java code runs on your webserver, so basically the only way to communicate between the two is via HTTP requests.
If you don't want to use AJAX, you could provide all of the relevant info when you submit the form to the server for validation. You could pass all the info you need to re-generate the form as it was, like which new fields are there and such
First, you'll need to add a new webservice to your Java webapp which performs validation. To achieve this, you could either add additional logic to your servlet (so that it looks for a request parameter like "doValidation=1" and performs validation if it's there) or write a different servlet that handles validation itself. You'll need to decide the format it should expect the form data in and how it should return the validation information.
On your frontend page, you'll need to modify the behavior of the form so that, when you need to do validation, it performs a request to this webservice and passes along the form data. I would probably do this with jQuery and do something like jQuery.ajax(...) and pass the contents of the form as a JSON object.
When your validation servlet returns data from the ajax call, you'll need to update the form based on the data it provides. If I was doing it, I would probably just have the servlet return a JSON object like {errorMessage:"..."} and I would use jQuery to add an element to the form containing the text of the validation error when it occurs. If the servlet returns an empty string or JSON object or something, I would consider it a validation success.
I'm working on a system for my university and I'm using the play framework to do that.
The Admin of this system sets a marker on a google map and I get the coordinates from that point.
Now I'm trying to pass this information to the server side, so that I might store these to Strings in a mySQL database. The only problem I have is passing the data from my String in javascript/JQuery to the java function.
I tried different solutions on the internet but some of them seemed outdated and I couldn't figure out how to do it.
I've only been programming in Java, Javascript, JQuery and PHP and have never used AJAX (like the $.get() methode from JQuery), but I think it might be pretty similar to what I know from PHP.
e.g.
http://java.dzone.com/articles/jquery-ajax-play-2
I'd like to pass my String with a button click to my java function, so I can store it in my db.
I'm really confused about this.
I know I can use something like
<a href="{#routes.Application.postMethod()}"> Send </>
and then mention the function in the routes like
POST /post controllers.Application.post();
but how do I pass my qjuery string?
and how do I store my String as a String in a java function like:
public static Result post(String Lat, String Lng){
???????????? EVOLUTION NEEDED ?????
}
Thanks in advance I really need your help :)!
I don't see why you are doing a POST, since this can be done using a GET request.
As per this example:
http://www.playframework.com/documentation/1.2/ajax#jsaction
We can see Play makes it easier using the jsAction tag. Lets assume you have the following route:
GET /admins/marker Admins.marker
Then in your HTML, at the bottom you'd do something like:
<script type="text/javascript">
$('#myButton').click( function() {
var action = #{jsAction #marker(':latitude',':longitude') /}
$('#result').load(
action({latitude: '23', longitude: $('#longitudeField').val }),
function() {
$('#content').css('visibility', 'visible')
}
)
});
</script>
In this case, the request will be sent like (example):
GET /admins/marker?latitude=23&longitude=67
And then on your backend, you need the have to java fn to deal with that route.
Basically the javascript/jquery, is called when #myButton element is clicked, then we generate the route URL we are going to make a request to using jsAction, then we make using load to make a GET request. You can change this to post too if you'd like.
I'm looking for a way to validate a single field at a time. This is so, while a user is filling in a form, each time the keypress or blur event occurs for each field, i can validate that field individually and show / hide its error message.
Is that possible? If so, how can I do it? Some google searching hasn't turned up any results which validate a single field, rather than the whole form.
You can use javax.validation.Validator#validateProperty() for that purpose.
I'd recommend that you try using Javascript Regular Expressions to validate user inputs and show/hide error messages.
I provided a code implementation example in the post at this link: Example using Regular Expresssions
Add an event listener to relevant input field in the DOM to provide responsiveness.
var letterField = document.getElementById('letterField'); // DOM element containing user input
letterField.addEventListener('keyup', function() { // key press event listener using anonymous function
if (event.keyCode === 13) { // run this code if the 'enter' key is pressed
if ( ... ) {
...
};
};
};
If you want to add effects, include the following code to transition the error message. Refer to the jQuery API for other effects:
userInputError.delay(800).fadeOut();
I have an ajax enabled list of records that I'm going through and each one has a dropdown box that I'm trying to make a required field for the form to submit. To complicate matters the 'Close Record' button is not the submit button so I can't just use required attribute on the select(dropdown box) that I'm using. The value for the selected dropdown box is saved in an Enterprise Java Bean so I thought I could just write a JavaScript function to check the value:
function CheckForm() {
var clearObj = document.getElementById("mySelect");
if(clearObj.value != "") {
return true;
} else {
clearObj.style.backgroundColor ='yellow';
}
return false;
}
This doesn't work because once I close one and go to the next it's maintaining the value of the previous record on the page. Basically I have an update-content event that I need to know how to handle. Any ideas as to how to manipulate the DOM or JSON object to make this select a required field? Thanks.
With the little information given, I would assume that when you close the existing record and then loading the next record, you are doing it through an ajax request. If thats the case, then you can add a call back for the ajax request, which would reset the drop down.
This should be a comment, but as you see, I dont have 50 points :-)
I am using the Sencha framework and am creating controls using Javascript. I want to fetch some data from the database using Java, but am uncertain on how to bind that Java object to the Sencha-created controls. What can I try?
'Sencha created controls'?
Check Sencha API for the controls - checkbox, gridpanel etc..
You may need to use a store config in most cases.
Just use Sencha GXT: "Sencha GXT is the fastest, most powerful way to create rich web-based applications using Java."
Suppose you want to create a combobox in sencha, then do it as:
var javaData = = [
[1, 'item1']
,[2, 'item2']
];
var combo = new Ext.form.ComboBox({
store: new Ext.data.SimpleStore({
id:0
,fields:
[
'myId', //numeric value is the key
'myText' //the text value is the value
]
,data: javaData
})
,valueField:'myId'
,displayField:'myText'
,mode:'local'
});
replace javaData var value with your data from server.
Ensure that the data is in json format to run this example.
For more: http://www.sencha.com/learn/combobox-faq/
What your ExtJS store does is an Ajax call to a certain page on your java application. That page will return data formatted in JSON so that your ExtJS store can parse that data.
Basically it doesn't mather what your back end technology is. You just need to make sure your page returns json in the following format:
{
data: [], //Array of json data
success: true, //true when your call was handled succesfull
total: 10 //The total items of a certain object
}
So in your case your JSP page will display the result in the JSON format as explained above, your ExtJS store will be configured to call that certain JSP page.