how to stop calling onbeforeunload event while page refresh - javascript

I am trying to update database while user closing browser/tap.I tried with onbeforeunload function and its working fine but even in page refreshing.Here is code what i tried
MyJSP :
<script type="text/javascript">
var refresh=false;
$(window).keydown(function(event){
if(event.keyCode==116)
{
refresh=true;
}
})
$(window).on('beforeunload', function(){
if(refresh==false)
{
$.get("BrowserCloseServlet", function() {
});
}
});
</script>
MyServlet :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
#SuppressWarnings("unused")
String getId = request.getParameter("getid");
Connection con = null;
PreparedStatement pst = null;
PreparedStatement pst2 = null;
ResultSet rst = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5", "root", "");
String query = "select NoOfCount from tbl_BroserCloseTable ";
String query2 = "update tbl_BroserCloseTable set NoOfCount= ? where Sno= ?";
// Statement st = con.createStatement();
// st.executeUpdate("");
pst = con.prepareStatement(query);
rst = pst.executeQuery(query);
if (rst.next()) {
int count = rst.getInt(1);
System.out.println("Actuall count is :" + count);
count -= 1;
pst2 = con.prepareStatement(query2);
pst2.setInt(1, count);
pst2.setInt(2, 1);
pst2.executeUpdate();
System.out.println("Updated successfully...");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
con.close();
rst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Its working fine(not update DB while click f5 button) but if the user click on refresh button then that servlet page called and updated DB.I want to stop calling onbeforeunload when click on refresh button in browser.
Update :
I only want to know how make that refresh=false; while click on refresh button in browser.
How to do this one?

Related

using datatables with JSP does not return the query data in the table and sends me an error

malfunction in ajax request in datatables returns me an error with the following message
DataTables warning: table id=tablaEstudiantes - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
revising on the console does not return me any value as below screenshot shown
as you can see in the ajax does not return any data attached the code in javascript
as you can see in the ajax does not return any data attached the code in javascript
<script>
$(document).ready(function() {
var tabla= $('#tablaEstudiantes').DataTable({
"destroy":true,
"processing":true,
"ajax":{
method:"POST",
url:"../ConsultaEstudiantes",
dataSrc:"datos"
},
columns:[
{data:"codigo"},
{data:"Nombres"},
{data:"Correo"},
{data:"Telefono"},
{data:"Estado"},
{data:"Campus"},
{data:"Facultad"},
{data:"Semestre"},
{data:"Modalidad"}
]
});
//$.fn.dataTable.ext.errMode = 'throw';
});
</script>
code used in servlet
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
Conexion conexion = new Conexion();
PreparedStatement pst = null;
ResultSet rs = null;
try {
String consulta = "SELECT estudiantes.Id_estudiante, estudiantes.Name_users, estudiantes.Mail_users,
estudiantes.Phone_users, estudiantes.Estado_usuario,
campus.Name_campus, faculta.Name, programa.Name_program,
estudiantes.Semestre, estudiantes.Modalidad FROM estudiantes, campus,
faculta, programa WHERE estudiantes.Id_campus = campus.Id_campus AND
faculta.Id=estudiantes.Id_faculty AND
programa.Id_program=estudiantes.Id_program;";
pst =(PreparedStatement) conexion.getConexion().prepareStatement(consulta);
rs = pst.executeQuery(consulta);
com.google.gson.JsonObject elementos = new com.google.gson.JsonObject();
com.google.gson.JsonArray array = new com.google.gson.JsonArray();
while(rs.next()){
com.google.gson.JsonObject item = new com.google.gson.JsonObject();
item.addProperty("codigo", rs.getString("estudiantes.Id_estudiante"));
item.addProperty("nombre", rs.getString("estudiantes.Name_users"));
item.addProperty("correo", rs.getString("estudiantes.Mail_users"));
item.addProperty("telefono", rs.getString("estudiantes.Phone_users"));
item.addProperty("estado", rs.getString("estudiantes.Estado_usuario"));
item.addProperty("campus", rs.getString("campus.Name_campus"));
item.addProperty("facultad", rs.getString("faculta.Name"));
item.addProperty("programa", rs.getString("programa.Name_program"));
item.addProperty("semestre", rs.getString("estudiantes.Semestre"));
item.addProperty("modalidad", rs.getString("estudiantes.Modalidad"));
array.add(item);
}
elementos.add("datos", array);
out.print(elementos.toString());
} catch (SQLException e) {
}finally{
try {
if(conexion != null) out.close();
if(pst != null) pst.close();
if(rs != null) rs.close();
} catch (SQLException e) {
System.out.println("Error 4: " + e);
}
}
}
I check but you are not sending me the ajax data or the type of error, I appreciate your collaboration is a small project that I am doing and I am new to the world of programming
I think
item.addProperty("codigo", rs.getString("estudiantes.Id_estudiante"));
item.addProperty("Nombre", rs.getString("estudiantes.Name_users"));
item.addProperty("Correo", rs.getString("estudiantes.Mail_users"));
item.addProperty("Telefono", rs.getString("estudiantes.Phone_users"));
item.addProperty("Estado", rs.getString("estudiantes.Estado_usuario"));
item.addProperty("Campus", rs.getString("campus.Name_campus"));
item.addProperty("Facultad", rs.getString("faculta.Name"));
item.addProperty("Programa", rs.getString("programa.Name_program"));
item.addProperty("Semestre", rs.getString("estudiantes.Semestre"));
item.addProperty("Modalidad", rs.getString("estudiantes.Modalidad"));
datatable must be case sensitive

How to avoid continuous alert on WebView Page Loading Finished?Android

I have a Webview In that I am giving Some Instructions Page on webview page loading finished
This is my sample code
public void onPageFinished(WebView view, String url) {
if (!getSharedPreferences("MainA_SP", MODE_PRIVATE)
.getBoolean("checkbox", false)) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainA.this);
LayoutInflater adbInflater = LayoutInflater.from(MainA.this);
View eulaLayout = adbInflater.inflate(R.layout.instpopup, null);
chkbx = (CheckBox)eulaLayout.findViewById(R.id.skip);
adb.setView(eulaLayout);
adb.setTitle("Welcome To Sample Page");
adb.setMessage(Html.fromHtml("App Instructions ....."));
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String checkBoxResult = "NOT checked";
if (chkbx.isChecked()) checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(MainA_SP, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
return;
} });
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String checkBoxResult = "NOT checked";
if (chkbx.isChecked()) checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(MainA_SP, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
return;
} });
SharedPreferences settings = getSharedPreferences(MainA_SP, 0);
String skipMessage = settings.getString("skipMessage", "NOT checked");
if (!skipMessage.equalsIgnoreCase("checked") ) adb.show();
}
try{
if (progressBar.isShowing()) {
progressBar.dismiss();
.
.
.
.
}
}catch(Exception exception){
exception.printStackTrace();
}
}
So Here Its working fine with Checkbox and sharedprefs
But the Problem Is that I have Given this alert in on page loading finished
So I am getting Alert multiple Times for a single url single page
I need to click the alert Every time I opens the App ... If I tick the Checkbox its not showing But For first run Alert is Showing Multiple Times
Update
I want to Show Alert on Page finished loading successfully
If you want to show alert at once after finished so you can use boolean value to check whether it is visible or not like below example.
private boolean alertVisiblity = false;
onPageFinished(){
//show your alert here
if(!alertVisiblity){
alertVisiblity = true;
new AlertDialog.Builder(MainActivity.this)
.setCancelable(false)
.setTitle("Alert")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
alertVisiblity = false; //or if you want to show it once never make it false or you can make it false before next call
}
}).show();
}

return dropdown list via ajax function call

I'm trying to return an arraylist via ajax function call and return the results to my HTML dropdown list.
Below is my ajax function, servlet code and html.
My dropdown list keeps coming back empty. Not sure where it is going wrong.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer p = Integer.parseInt(request.getParameter("studentid"));
ArrayList<SessionDataBean> result = new ArrayList<>();
String sessid = null;
try ( Connection con = JdbcUtil.getConnection()) {
String sql= "select distinct F.SESSIONID "
+ "from Students F "
+ "where F.studentid = "+p;
try (Statement st = con.createStatement()) {
System.out.println(sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
result.add(new SessionDataBean(rs.getString(1)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
response.setContentType("application/json");
new Gson().toJson(result, response.getWriter());
}
Ajax function call code:
function listSession(){
var name = document.getElementById("studentid").value;
$.ajax({
url : "<%=context%>/ListSessionsServlet?studentid=" + name,
type : "POST",
async : false,
dataType: "json",
success : function(data) {
var toAppend = '';
$.each(data,function(i,o){
toAppend += '<option>'+o.id+'</option>'; <---issue might be here?
});
$('#sessid').append(toAppend);
}
});
}
HTML code:
<div class="cell">
Select Session for Student
<div class="input-control select mutiple full-size">
<select id="sessid" name="sessid">
</select>
</div>
</div>
Server is expecting a POST parameter "studentid" at
Integer p = Integer.parseInt(request.getParameter("studentid"));
though "name" is passed. Substitute
url : "<%=context%>/ListSessionsServlet?studentid=" + name
for
url : "<%=context%>/ListSessionsServlet?name=" + name

asp.net Dropdownlist not refreshing after being removed

I have a 2 drop down lists with company name and company addresses and a remove button linked to a stored procedure. Addresses is not being refreshed even though I am calling databind() on that address drop down List. Can anyone point me out in the right direction?
//Button to remove Company
protected void btnremovecompany_2(object sender, EventArgs e)
{
if (ddlcompanyaddress2.SelectedIndex != 0) /*checked to see if an address is Selected first*/
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")/* if yes is clicked then procedd to deactivate that company address*/
{
String strConnString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_update_company_active";
cmd.Parameters.Add("#companyname", SqlDbType.VarChar).Value = ddlcompany2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = ddlcompanyaddress2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#category", SqlDbType.VarChar).Value = ddlTrades2.SelectedItem.Text.Trim();
cmd.Connection = con;
**ddlcompanyaddress2.DataBind();**
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
/*Display message saying company is deactivated*/
string message = "Company has been removed";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
con.Close();
con.Dispose();
}
}
else
{
/*if canceled is clicked then display no changes*/
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('No Changes were made!')", true);
}
}
else
{
string message = "Please pick an address first.";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
}
You might be missing the datasource for your dropdown list. I am unable to find datasource in your code. You have just called databind method.
Can you please bind the datasource?
added this code to the try{} area and it resets all the dropdowns with fresh data.
ddlgettrades2();
getcompany2(ddlTrades2.SelectedItem.Text);
getaddress2(ddlcompany2.SelectedItem.Text);

remove element from master page on button click

So here is the deal I am working on a simple project, with a log in form and a sign up form. In the beginning you will see this which is displayed in the picture.
After you sign up or log in, then you will get what is displayed in the picture below
When I click on a new page for example: like on the home page, videos, contact, then it will just return back to its original state in the first picture. I want to prevent that and keep it the way it is in the second picture until you click on log out. I have been looking everywhere for answers and can't seem to find exactly what I am looking for.
Here is a little code from what I have used to try and accomplish this
HTML code, which is located in the master page
<a id ="LogIn" runat="server" href="../LogIn.aspx">Log In:</a>
<a id ="SignUp" runat="server" href="../SignUp.aspx">Sign Up:</a>
<a id ="LogOut" href="../LogIn.aspx">Log Out:</a>
CSS code in the master page as well.
#LogIn
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 767px;
}
#SignUp
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 867px;
}
#LogOut
{
margin-top: 30px;
font-size: 20px;
position: absolute;
margin-left: 880px;
display: none;
}
Okay I have tried doing it in javascript, which is in the master page
function showAlert() {
$(".SignUp").slideUp("25000");
$(".LogIn").slideUp("25000");
$(".CreateAccount").hide();
$(".AccountLogIn").hide();
$("h1").remove();
$("#LogIn").remove();
$("#SignUp").remove();
$("#LogOut").show();
}
the showalert function is being called from the button click event in C# for the LogIn form and SignUp form
SqlConnection connection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
connection.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=**************";
connection.Open();
}
public void CheckEmail()
{
SqlCommand Comm = new SqlCommand("select count(*) from SignUp where Email ='" + Email.Text + "'", connection);
Comm.Parameters.AddWithValue("#Email", Email.Text);
Comm.Connection = connection;
int count = Convert.ToInt32(Comm.ExecuteScalar());
if (count > 0)
{
Thread.Sleep(3000);
VerifyEmail.Visible = true;
}
else
{
Thread.Sleep(5000);
InsertData();
VerifyEmail.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
}
}
public void InsertData()
{
SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(#FirstName, #LastName, #Password, #Email)", connection);
Command.Parameters.AddWithValue("#FirstName", FirstName.Text);
Command.Parameters.AddWithValue("#LastName", LastName.Text);
Command.Parameters.AddWithValue("#Password", Password.Text);
Command.Parameters.AddWithValue("#Email", Email.Text);
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
LogIn.Visible = false;
SignUp.Visible = false;
Command.ExecuteNonQuery();
}
protected void SignUp_Click(object sender, EventArgs e)
{
CheckEmail();
connection.Close();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert()", true);
//Response.Write("<script language=JavaScript> alert('You have Successfully created an Account'); </script>");
//Response.Redirect("~//Default.aspx");
}
I also tried doing it in the back end code as well shown above. It also shows how the user is being loged in and saved in the database. That is being called in the button click event, when you click to create an account or click to log into an account.
LogIn.aspx.cs
SqlConnection conn = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
conn.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=*******";
conn.Open();
}
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
public void ExecuteLogIn()
{
SqlCommand Command = new SqlCommand("select ISNULL(Email, '') As Email, ISNULL(Password, '') As Password from SignUp where Email='" + Email.Text + "'", conn);
SqlCommand Command2 = new SqlCommand("select * from SignUp where FirstName= #FirstName", conn);
Command2.Parameters.AddWithValue("#FirsName", FirstName.Text);
SqlDataReader dr = Command.ExecuteReader();
string UserEmail = Email.Text;
string UserPassword = Password.Text;
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
while (dr.Read())
{
if (this.CompareStrings(dr["Email"].ToString(), UserEmail) &&
this.CompareStrings(dr["Password"].ToString(), UserPassword))
{
InvalidLogIn.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
//LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
LogIn.Visible = false;
SignUp.Visible = false;
}
else
{
InvalidLogIn.Visible = true;
}
}
//Command.Parameters.AddWithValue("#Password", Password.Text);
//Command.Parameters.AddWithValue("#Email", Email.Text);
conn.Close();
}
protected void LogIn_Click(object sender, EventArgs e)
{
ExecuteLogIn();
}
Any help would be greatly appreciated thanks so much
The code is missing too many pieces. I could only give you a direction. If you have specific question about FormAuthentication, please create a new question.
CheckEmail method is prone to SQL Injection attack. You want to consider using Parameterized Query.
We normally need both username*(or email)* and password to validate an account. Easiest way to implement authentication in ASP.NET Web Form is to use FormAuthentication.
The following is the sample code. I also created a sample project at GitHub, so that you can test it.
Sign-In method inside Login.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
string username = UsernameTextBox.Text,
password = PasswordTextBox.Text;
bool rememberMe = RememberMeCheckBox.Checked;
// Retrieve username and hashed password from database, and validate them
if (username.Equals("johndoe", StringComparison.InvariantCultureIgnoreCase) &&
password.Equals("123456", StringComparison.InvariantCultureIgnoreCase))
{
FormsAuthentication.RedirectFromLoginPage(username, rememberMe);
}
MessageLabel.Text = "Invalid username or password";
}
Global.asax.cs
We then retrieve username from cookie, and save it in Principal Object.
public class Global : HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (decryptedCookie != null)
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(decryptedCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
}
web.config
Please ensure authentication tag is in web.config.
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>
Usage
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
}
}

Categories

Resources