I have created a datatable in Struts2 and also have a feature of adding a record into this table by some action. After the record is inserted we are refreshing the page to get the table refreshed.
I had tried to use Ajax for this purpose and send the new values we have inserted to the Action class by request parameter and in the response we are getting the table refreshed.
My Ajax function is:
function reloadTable(){
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser has no AJAX Support!");
return false;
}
}
}
var elem1 = document.getElementById('host0');
var elem2 = document.getElementById('ip0');
var elemTable = document.getElementById('hostTable');
//alert(indexSelected);
//alert(document.getElementById(elem).options[indexSelected].value);
var url = "insertTable.action";
ajaxRequest.open("POST", url, true);
ajaxRequest.onreadystatechange = function()
{
try
{
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var res = ajaxRequest.responseText;
if (res)
{
//alert("hi"+res.greeting);
document.getElementById("hostTable").innerHTML = res;
//adjustTable();
}
}
}
catch (e)
{
}
};
//alert(selectedCountry);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var hostName = elem1.value;
var ipAddress = elem2.value;
//alert("AJAX CALL"+elem1.value+elem2.value);
//ajaxRequest.send("hostName="+elem1.value+"&ipAddress="+elem2.value);
ajaxRequest.send("hostName="+hostName+"&ipAddress="+ipAddress);
//ajaxRequest.send(null);
}
Content in my Struts.xml is:
<action name="insertTable" method="insertNewData" class="action.LoginAction">
<result name="success">/success.jsp</result>
</action>
Method in my action class:
public String insertNewData(){
populateList();
System.out.println("Hi"+getHostName()+getIpAddress());
userNameList.add(new UserType(hostName,ipAddress));
return SUCCESS;
}
Now I want the list populated in the actionClass method to be reflected in the table by this Ajax call. In this method I am appending the value that I am sending through parameter in the Ajax method. I can fetch the new values in the action class method but while sending the response the whole page is displayed in place of the table.
Thanks,
Sachin
After the record is inserted we are refreshing the page to get the
table refreshed.
Is it like you don't want to refresh the whole page for that. In that case I suggest you to use Struts2 Jquery Plugin. Grid showcase does exactly what you want to do.
For more examples you can visit Online Examples and can request can example if you want something more specific.
Related
I have an e-commerce simulation web app for buying movies and I want a popup small window to appear when a user mouses over the movie's id and display info and give them the option to add that movie to their cart (like how Facebook displays users info when you mouseover one of your friend's names). I have a java servlet that receives the movie's id and gets the proper info from my database and sends it back to the JSP, but form there I don't know how to properly use AJAX or jquery to display the window with the proper info.
SERVLET CODE
int movie_id = Integer.parseInt((String) request.getParameter("movie_id"));
StringBuilder query = new StringBuilder("select * from movies where movies.id =");
query.append(movie_id);
// Perform the query
MySQLHandler sql_handler = new MySQLHandler( );
sql_handler.execute_query( query.toString() );
ResultSet result = sql_handler.get_result();
try {
Movie movie = createMovie(result);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(movie.getTitle());
request.setAttribute("movie", movie);
}
catch(SQLException e) {
e.printStackTrace();
}
}
JAVASCRIPT CODE
function ajaxFunction(movie_id){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
alert(movie_id);
var parameter = "movie_id=" + movie_id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
, "application/x-www-form-urlencoded") //Needed for post request for some reason. //http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
ajaxRequest.send(parameter);
}
$.ajax({
url: 'route/to/videoinfo' + specificVideoId,
type: "POST",
contentType: "application/json ;charset=UTF-8",
}).done(function(result){
(if you rendered out the html already just do)
var containerDiv = document.getElementById("#idOfDivToFill")
containerDiv.innerHTML = result
}).fail(function(err){
console.log(err)
})
Someone let me know if this is terrible.
I am entering data into a jsp page and validating it from the database. I need to give an alert on the JSP page if the validation is false without refreshing the page as the user is forced to re-enter all the details when the page is refreshed:
My validation Method:
public boolean accountCifMismatch(String account, String custid) {
Connection conn;
int count = 0;
try {
conn = db.getDbConnection();
String sql = pr.getDBProperty().getProperty("com.crb.accountCifMismtach");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, account);
ps.setString(2, custid);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
}
DBConnection.closeConn(conn);
System.out.println(MemoryListener.getMemoryDetails());
} catch (Exception asd) {
System.out.println(asd.getMessage());
return false;
}
return count == 0;
}
My servlet call:
Fraud fmd = new Fraud();
if (!fmd.accountCifMismatch(account_no, cust_id)) {
//Continue Processing
} else {
session.setAttribute("accountcifmismtach", true);
session.setAttribute("content_page", "fraud.jsp");
}
and on fraud.jsp I call a javascript:
<script type="text/javascript">
if (${accountcifmismtach == 'true'}) {
alert("Account Number CIF Mismtach");
}
</script>
EDIT I am submitting the form:
<form id="form1" name="form1" method="post" action="do?MOD=BOK&ACT=doFindFraud">
</form>
The alert shows and then the page is refreshed, so the user has to input all the details once more. How can I show the alert without refreshing the page?
If you want to validate the Form without refreshing the Page , You need to use AJAX .
There are many ways to make ajax calls but with Java Programming Language I prefer DWR(Direct Web Remoting)Easy AJAX for java
DWR Way :
http://directwebremoting.org/dwr/documentation/index.html
Other Famous ways listed below :
JQUERY Way
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
JavaScript (No Jquery Required)
function AJAXPost(formId) {
var elem = document.getElementById(formId).elements;
var url = document.getElementById(formId).action;
var params = "";
var value;
for (var i = 0; i < elem.length; i++) {
if (elem[i].tagName == "SELECT") {
value = elem[i].options[elem[i].selectedIndex].value;
} else {
value = elem[i].value;
}
params += elem[i].name + "=" + encodeURIComponent(value) + "&";
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
Write return false after alert and focus the required input form element in javascript.
Ex: docuemnt.getElementById('requiredInputElement').fous;
So in my company we use SOAP API to get connect to our system, and I'm pretty well rehearsed in it and can use all the calls.
I just want to know where should I start if I want to build a test landing page that can execute the API queries.
I would prefer to do it with JavaScript if that is possible as we don't have PHP installed on our servers.
Looking for some direction of where to start - I'm simply going to take a value from a text box and place within the XML request and execute it :)
Any pointers appreciated!
<script>
function fireRequest(){
..
//parse your SOAP Request and set the request with 'dataContent'
...
var url = //your target gateway here Java/PHP or your web service recpetor
var postStr =//xml SOAP resquest ;
makeRequest(url, postStr);
}
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Mozilla, Safari ...
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
} else {
alert("Your Browser does not support XMLHTTP");
}
}
function makeRequest(url, param) {
//If our readystate is either not started or finished, initiate a new request
//clearing all divs
receiveReq = getXmlHttpRequestObject();
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
//Set up the connection to captcha_test.html. True sets the request to asyncronous(default)
receiveReq.open("POST", url, true);
//Set the function that will be called when the XmlHttpRequest objects state changes
receiveReq.onreadystatechange = responseHandler;
//Add HTTP headers to the request
receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
receiveReq.setRequestHeader("Content-length", param.length);
receiveReq.setRequestHeader("Connection", "close");
//Make the request
receiveReq.send(param);
}
}
function responseHandler(){
if (receiveReq.readyState == 4) {
var response = receiveReq.responseText;
if(response){
//do what ever you want with the response XML
}
}
}
</script>
This would be enough for your case. use the methods at your page.
I am very new to this
I have this link:
<a onclick = sendRequest('GET','room_chart.jsp') href=#>Show Chart</a>
but I need to generate dynamic address inside that link.
I created javascript:
<script language="javascript">
var selectedOption;
var ROOM;
var BUILDING;
function GetLink(){
selectedOption = document.getElementById("roomandbuildingid").options[e.selectedIndex].text; //getting selected option
ROOM = selectedOption.split("|")[0].trim().split(":")[1].trim(); //parsing text
BUILDING = selectedOption.split("|")[1].trim().split(":")[1].trim(); //parsing text
return "'room_chart.jsp?room="+ROOM+"&building="+ BUILDING+"'"; //returning url
}
</script>
but when I paste the function into it- it does not work!
<a onclick = sendRequest('GET',GetLink()) href=#>Show Chart</a>
Now, after debug, I found out that actually it creates the proper srting, but somehow my function is not willing to accept it as URL! It is quite a paradox- it creates correct string- if I hardcode it into the code- it works! But dynamic links from variables - don't work!
please help!
see below:
my js file:
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
// alert( document.URL );
// document.write (GetLink());
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
OK, the function was returning everything correctly, the parsing was not done right. I fixed it. JavaScript is hard for me to debug.
How can I refresh a particular part of a web page with a time interval (not entire page)?
You can use Ajax for your purpose.
suppose you want to check username availability before registering a user to your site.
create a request object asynchronously
function createRequest()
{
try{
request=new XMLHttpRequest();
} catch(tryMS){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
} catch(otherMS){
try{
request=new ActiveXObject("Microsoft.XMLHTTP");
} catch(failed) {
request=null;
}
}
}
return request;
}
Next is the code to send a asynchronous request
function checkAvailability (username) {
request=createRequest();
if(request==null){
alert("Ajax request not possible on your browser");
return;
}
var url="checkAvailability?username="+username;
request.open("GET", url, true);
request.onreadystatechange = showStatus;
request.send(null);
}
Track the response
function showStatus () {
if(request.readyState == 4) {
if(request.status == 200) {
var response = request.responseText;
if(response == 1){
//username available
} else{
//username not available
}
}
}
}
Suppose you have a DIV in your your Web Page that you want to refresh :
<div id="myDiv"> </div>
To refresh it using javascript you just have to select it and change the html code :
document.getElementById("myDiv").innerHtml = "Your new html code to display"
If you want to deal with forms, database queries ...
You have to use AJAX to call some php scripts for example without reloading the current page ...
You are talking about AJAX
Look at http://api.jquery.com/jQuery.ajax/ for jQuery
But please consider learning the underlying javascript language - you will be better for it in the long run
here is a simple example
http://www.degraeve.com/reference/simple-ajax-example.php
The history behind ajax can be found here http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications