Passing two parameters using ajax and getting the values of parameters in another page - ajax

how can i pass two parameters using ajax from two different textboxes to another page.
which function should i use to do this.
Index.jsp
<html>
<head>
<script type="text/javascript">
function sendInfo(str,stri)
{
var XMLhttp;
if(str=="")
{
document.getElementById("my").InnerHTML="";
}
if(window.XMLHttpRequest)
{
XMLhttp=new XMLHttpRequest();
}
else
{
XMLhttp=new ActiveXObject("Microsoft.XMLhttp");
}
XMLhttp.onreadystatechange=function()
{
if(XMLhttp.readyState==4 && XMLhttp.status==200)
{
document.getElementById("my").innerHTML=XMLhttp.responseText;
}
}
XMLhttp.open("GET","get.jsp?feeid="+str+"&sid="+stri,true);
XMLhttp.send();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>fee processing</title>
</head>
<body>
<h3>Fee Transaction</h3>
<form method="post" action="myservlet">
<table>
<tr>
<td>Date of Transaction</td>
<td><input type="text" name="date"/></td>
</tr>
<tr><td>Feeid</td>
<td><input type="text" name="feeid" onkeyup ="sendInfo(this.value)"></td></tr>
<tr><td>Student Id</td><td><input type="text" name="sid" onkeyup="sendInfo(this.value)"/></td></tr>
<tr><td><div id="my"></div></td></tr>
<tr><td>amount</td>
<td><input type="text" name="amount"/></td></tr>
<tr><td>Remaining</td>
<td><input type="text" name="remain"/></td>
</tr>
<tr><td><input type="submit" name="submit" value="submit"></td></tr>
</table>
</form>
</body>
</html>
get.jsp: i want those two parameter values in this page.
</head>
<body>
<form method="post" action="index.jsp">
<% String fid = request.getParameter("feeid");
int fidd =Integer.parseInt(fid);
System.out.print(fid);
String sid = request.getParameter("sid");
int sidd = Integer.parseInt(sid);
try
{
//int i =3;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/mdb","root","tiger");
Statement stmt = con.createStatement();
//System.out.print("a");
String query1 = "select amount from feestudent where st_id="+sidd+" and fees_id="+fidd;
ResultSet rs = stmt.executeQuery(query1);
if(rs.next())
{
// System.out.print("d");
%>
<table>
<tr>
<td><input type="text" name = "totalamt" value="<%=rs.getInt("amount") %>"/></td>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</tr>
</table>
%>
</form>
</body>
</html>
please Help me.
Thanks.

The problem in your code is caused by this line in the HTML:
<td><input type="text" name="feeid"
"which function should i use here?" ="sendInfo(this.value)"></td>
Your sendInfo(str, stri) JavaScript function expects two parameters, but you are only passing in one. Pass in a value for stri and you should be good to go.

Related

have HTTP error "Unable to compile class for JSP"

I am working in a JSP project. While runnning the project using Netbeans with Tomcat 7.0.68 server, I got the following exception,
HTTP Status 500 - Unable to compile class for JSP:
HTTP Status 500 - Unable to compile class for JSP:
**type** Exception report
**message** Unable to compile class for JSP:
**description** The server encountered an internal error that prevented it from fulfilling this request.
**exception**
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: [14] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
The import com.sun.corba.se.spi.presentation.rmi.StubAdapter.request cannot be resolved
An error occurred at line: [14] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
Syntax error on token "(", . expected
An error occurred at line: [16] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
The import String cannot be resolved
An error occurred at line: [17] in the generated java file: [C:\apache-tomcat-7.0.68\work\Catalina\localhost\Rites1\org\apache\jsp\Register_jsp.java]
Syntax error on tokens, Name expected instead
**Stacktrace**:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:490)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:379)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:341)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:662)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:364)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.68 logs.
Apache Tomcat/7.0.68
I'm building a registration form in a file called Register.jsp in a maven project using netbeans
<%#page import="com.sun.corba.se.spi.presentation.rmi.StubAdapter.request(
Object, String, boolean)"%>
<%#page import="java.lang.ClassNotFoundException"%>
<%#page import="java.io.FileNotFoundException"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.io.FileInputStream"%>
<%#page import="java.io.File"%>
<%#page import="javax.swing.JComboBox"%>
<%#page import="javax.swing.JTextField"%>
<%#page import="javax.swing.JRadioButton"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<% Class.forName("com.mysql.jdbc.Driver");%>
<%#page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" ></meta>
<link rel="stylesheet" type="text/css" href="CSS/RitesCSS.css"/>
<link rel="stylesheet" type="text/css" href="CSS/Resize.css" media="screen and (max-widht:1000px)"/>
<link rel="stylesheet" type="text/css" href="CSS/Menu.css"/>
<link rel="stylesheet" type="text/css" href="CSS/Layout.css"/>
<style type="text/css">
body{
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
}
</style>
<title>Register Now</title>
</head>
<body>
<%!
public class Followers {
String URL = "jdbc:mysql://localhost:3306/rites";
String USERNAME = "myusername";
String PASSWORD = "mypass";
Connection connection = null;
PreparedStatement insertUsers = null;
ResultSet resultSet = null;
public Followers() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
insertUsers = connection.prepareStatement(
"INSERT INTO followers (HajjID,UserName,ID,Phone,Country,Passport,Language,Gender,Photo,Password,State,DOB,adress)"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?);"
);
} catch (SQLException e) {
e.printStackTrace();
}
}
public int setFollowers(String HajjID, String UserName, String ID, String Phone, String country, String PassportNo, String Language, String rdoGender, String img, String txtPassword, String States, String DoB, String txtarAddress) {
int result = 0;
FileInputStream fis = null;
File Photo = new File("");
img = fis.toString();
try {
insertUsers.setString(1, HajjID);
insertUsers.setString(2, UserName);
insertUsers.setString(3, ID);
insertUsers.setString(4, Phone);
insertUsers.setString(5, country);
insertUsers.setString(6, PassportNo);
insertUsers.setString(7, Language);
insertUsers.setString(8, rdoGender);
try {
fis = new FileInputStream(Photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
insertUsers.setString(9, img);
insertUsers.setString(10, txtPassword);
insertUsers.setString(11, States);
insertUsers.setString(12, DoB);
insertUsers.setString(13, txtarAddress);
result = insertUsers.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
%>
<%
int result = 0;
if (request.getParameter("submit") != null) {
String Type = new String();
String HajjID = new String();
String UserName = new String();
String ID = new String();
String Phone = new String();
String country = new String();
String PassportNo = new String();
String Language = new String();
String rdoGender = new String();
String Photo = new String();
String txtPassword = new String();
String States = new String();
String DoB = new String();
String txtarAddress = new String();
if (request.getParameter("Type").toString() != null) {
Type = request.getParameter("Type").toString();
}
if (request.getParameter("HajjID").toString() != null) {
HajjID = request.getParameter("HajjID").toString();
}
if (request.getParameter("ID").toString() != null) {
ID = request.getParameter("ID").toString();
}
if (request.getParameter("Phone").toString() != null) {
Phone = request.getParameter("Phone").toString();
}
if (request.getParameter("country").toString() != null) {
country = request.getParameter("country").toString();
}
if (request.getParameter("PassportNo").toString() != null) {
PassportNo = request.getParameter("PassportNo").toString();
}
if (request.getParameter("Language").toString() != null) {
Language = request.getParameter("Language").toString();
}
if (request.getParameter("rdoGender").toString() != null) {
rdoGender = request.getParameter("rdoGender").toString();
}
if (request.getParameter("Photo").toString() != null) {
Photo = request.getParameter("Photo").toString();
}
if (request.getParameter("txtPassword").toString() != null) {
txtPassword = request.getParameter("txtPassword").toString();
}
if (request.getParameter("States").toString() != null) {
States = request.getParameter("States").toString();
}
if (request.getParameter("DoB").toString() != null) {
DoB = request.getParameter("DoB").toString();
}
if (request.getParameter("txtarAddress").toString() != null) {
txtarAddress = request.getParameter("txtarAddress").toString();
}
Followers users = new Followers();
result = users.setFollowers(HajjID, UserName, ID, Phone, country, PassportNo, Language, rdoGender, Photo, txtPassword, States, DoB, txtarAddress);
}
%>
<form id="form1" runat="server" action="register.php" method="POST">
<div id="contaner">
<div id="header">
<img src="logo.jpg" align="left"></img>
<h1> Rites</h1>
<li>Register now</li>
</div>
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Rites</li>
<li>Contact us</li>
<li>Login</li>
</ul>
</div>
<div id="mainbody">
<div id="pageHeading"> <v>Registeration</v></div>
<div id="bodyLeft">
</div>
<div id="bodyRight"><h5>
<form name="registration" action="RegServlet" method="post" id="registerForm">
<table id="table1">
<tr>
<td>User name</td>
<td><input type="text" name="UserName" id="txt" class='StyleTxtField'/></td>
</tr>
<tr>
<td>ID</td>
<td><input type="text" name="ID" id="txt" class='StyleTxtField'/></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="Phone" id="txt" class='StyleTxtField'/></td>
</tr>
<tr>
<td>Country</td>
<td><select name="country" id="txt" class='StyleSelectFiled'>
<option value="">Country...</option>
<option value="Afganistan">Afghanistan</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
</select></td>
</tr>
<tr>
<td>Date of Birth</td>
<td>
<input type="date" name="DoB" id="txt" class='StyleTxtField'/>
</td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="txtarAddress" id="txt" class='StyleTxtField'></textarea>
</td>
</tr>
<tr>
<td>Type</td>
<td><input type="radio" name="Type" id="Leader" value="Leader" ><label for="Leader">Leader</label>
<input type="radio" name="Type" id="Follower" value="Follower" onsubmit="setFollowers"><label for="Follower">Follower</label></td>
</tr>
<tr>
<td></td>
<input type="hidden" name="hidden" value="<%= result%>" />
<td><br><button type="reset" id="btm"><m>Reset</m></button>
<button type="submit" id="btm"><m>Register</m></button></td>
</tr>
</table><br>
</form></h5>
<SCRIPT language="JavaScript">
<!--
function dusplayResults()
{
if (document.myForm.hidden.value === 1) {
alert("Data Inserted1!");
}
}
</SCRIPT>
</div>
</div>
</div>
</form>
</body>
</html>
i want to do this "if the chosen radio button named "type" is follower insert the data into the follower table, and if the chosen radio button named "type" is leader insert the data into the leader table"
I'm using a database called rites in phpmyadmine
<%#page import="com.sun.corba.se.spi.presentation.rmi.StubAdapter.request(
Object, String, boolean)"%>
your import is wrong.
use
<%# page import="static com.sun.corba.se.spi.presentation.rmi.StubAdapter.register" %>

I'm not able to excute perl script inside ajax

I have set of AJAX code, that code call a Perl Script and script have some functionality.Whenever i click on Dial button Perl script should be run but i'm not able to run script.When i click on dial button my complete Perl program is showing on Web.On other had when i execute my program forcefully it executed properly.
HTML Code
<!CTYPE html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<title>Outbound Calling Demo Site</title>
<script language="Javascript">
function doDial(phone)
{
var phone_no = document.getElementById('phone').value;
// alert(phone_no);
var ajaxRequest; // The variable that makes Ajax possible!
if (window.XMLHttpRequest)
{ //Opera 8.0+, Firefox, Safari
ajaxRequest= new window.XMLHttpRequest();
}
else
{
try {
ajaxRequest= new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch (e) {}
try { ajaxRequest= new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { ajaxRequest= new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
function handler()
{
if (ajaxRequest.readyState==4 && ajaxRequest.status==200)
{
document.getElementById("ajaxDiv").innerHTML=ajaxRequest.responseText;
}
}
var queryString = "?phone=" + phone_no ;
get_selected_data(document.getElementById('agent'));
if(ajaxRequest != null)
{
ajaxRequest.open("POST", "dial_call2.pl" + queryString , true);
ajaxRequest.onreadystatechange = handler;
//console.log(queryObj.fund);
ajaxRequest.send(null);
}
else
{
window.console.log("AJAX (XMLHTTP) not supported.");
}
}
</script>
<table >
Number to dial: <input class="text_box" name="phone" type="text" id="phone" size="14" value="" />
<input type="button" value="Dial" onClick="javascript:doDial();"/>
<div id='ajaxDiv'></div>
<tr>
<td><input type="button" name="dtmf1" value='1' id="dtmf1" onClick="sendDTMF(1);"/></td>
<td><input type="button" name="dtmf2" value='2' id="dtmf2" onClick="sendDTMF(2);"/></td>
<td><input type="button" name="dtmf3" value='3' id="dtmf3" onClick="sendDTMF(3);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmf4" value='4' id="dtmf4" onClick="sendDTMF(4);"/></td>
<td><input type="button" name="dtmf5" value='5' id="dtmf5" onClick="sendDTMF(5);"/></td>
<td><input type="button" name="dtmf6" value='6' id="dtmf6" onClick="sendDTMF(6);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmf7" value='7' id="dtmf7" onClick="sendDTMF(7);"/></td>
<td><input type="button" name="dtmf8" value='8' id="dtmf8" onClick="sendDTMF(8);"/></td>
<td><input type="button" name="dtmf9" value='9' id="dtmf9" onClick="sendDTMF(9);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmf*" value='*' id="dtmf*" onClick="sendDTMF(this.value);"/></td>
<td><input type="button" name="dtmf0" value='0' id="dtmf0" onClick="sendDTMF(0);"/></td>
<td><input type="button" name="dtmf#" value='#' id="dtmf#" onClick="sendDTMF(this.value);"/></td>
</tr>
<tr>
<td><input type="button" name="dtmfClr" value="Clr" onClick="number_clear(this.value);"/></td>
<td><input type="button" name="dtmfC" value="C" onClick="number_c(this.value);"/></td>
</tr>
</table>
<tr>
<th>
<td><input type="button" id="hangup" value="Hangup" onClick="javascript:doHangup();"/></td>
<td><input type="button" id="unregister" value="Unregister" onClick="javascript:doUnregister();"/></td>
<td><input type="button" id="answer" value="Answer Call" onClick="javascript:doAnswer();" style="visibility:hidden;"/><br/></td>
</th>
</tr>
</form>
</body>
</html>
Perl Code :-
#!/usr/bin/perl
use strict;
use CGI;
my $cgi = new CGI;
use CGI::Carp qw(fatalsToBrowser);
use IO::Socket;
print $cgi->header();
print $cgi->start_html('Asterisk Caller');
print '<center><p>call</p>';
my ($request,#phone_no,$phone_no);
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$request = $ENV{'QUERY_STRING'};
}
elsif ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $request,$ENV{'CONTENT_LENGTH'}) || die "Could not get query\n";
}
my #phone_no=split(/=/,$request);
my $phone_no;
my $phone_number = $phone_no[1];
chomp($phone_number);
my $host = '127.0.0.1';
my $login = "Action: login\r\nUsername: lite\r\nSecret: 4003\r\n\r\n";
$/ = "\r\n"; # <> reads a single line for signon banner
# Code for making connection with Telnet
my $s = IO::Socket::INET->new("$host:5038") or die "can't connect to $host: $!\n";
my $banner = <$s>; # read the banner
my $line = ('-' x 78)."\n";
print $banner,$line;
print $s $login;
my $resp = <$s>;
print $resp,$line;
print $s "Action: Originate\r\nChannel: DAHDI/42/$phone_number\r\nContext: oreilly\r\nExten: s\r\nCallerID: 7702009896\r\nPriority: 1\r\nWaitTime: 10\r\nRetryTime: 20\r\nMaxRetries: 2\r\n\r\n";
$resp = <$s>;
print $resp,$line;
print $s "Action: Logoff\r\n\r\n";
$resp = <$s>;
print $resp,$line;
close $s;
If you are using Apache and running on a Linux server, then the following may help.
You may need the following .htaccess file alongside your Perl code:
<FilesMatch "\.pl$">
Options +ExecCGI
SetHandler cgi-script
</FilesMatch>
For this to work you'd also need to ensure that the Perl script is executable:
chmod 755 myscript.pl
.. and that the first line of the script is something like:
#!/usr/bin/perl

Exception "jdbc.odbc.JdbcOdbcDriver" while inserting into oracle database using jsp

I used simple JSP code to insert 5 fields into my oracle 10g database.
And on submitting form I receive an exception "jdbc.odbc.JdbcOdbcDriver".
I am unable to understand what is the problem.
please help me out.
My code is as follows:
signup.html
<html>
<head><title>Sign up</title>
<link rel="stylesheet" type="text/css" href="default.css">
<link rel="stylesheet" type="text/css" href="align.css">
<script language="javascript">
function validation(Form_obj)
{
if(Form_obj.fnametxt.value.length==0)
{
alert("Please, fill up the first name!!!");
Form_obj.fnametxt.focus();
return false;
}
if(Form_obj.lnametxt.value.length==0)
{
alert("Please, fill up the last name!!!");
Form_obj.lnametxt.focus();
return false;
}
if(Form_obj.usrnametxt.value.length==0)
{
alert("Please, fill up the user name!!!");
Form_obj.usrnametxt.focus();
return false;
}
if(Form_obj.pswdtxt.value.length==0)
{
alert("Please, fill up the password name!!!");
Form_obj.pswdtxt.focus();
return false;
}
if(Form_obj.phonetxt.value.length==0)
{
alert("Please, fill up the phone number!!!");
Form_obj.phonetxt.focus();
return false;
}
return true;
}
</script>
</head>
<h1>Jobs Portal</h1>
<div id="sign">Sign up</div>
<center>
<form id="form" action="signup.jsp" method="post" name="signform" onSubmit="return validation(this)">
<table border="3" cellpadding="0" cellspacing="0">
<tr><td>
<table>
<tr><td colspan="2" align="center">Fill your details</td></tr>
<tr><td colspan="2"> </td></tr>
<tr><td>First Name</td><td><input type="text" name="fnametxt"></td></tr>
<tr><td>Last Name</td><td><input type="text" name="lnametxt"></td></tr>
<tr><td>User Name</td><td><input type="text" name="usrnametxt"></td></tr>
<tr><td>Password</td><td><input type="password" name="pswdtxt"></td></tr>
<tr><td>Mobile no.</td><td><input type="text" name="phonetxt"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" name="signbt" value="Sign up" > </td></tr>
</td></tr>
</table>
</form>
</center>
</html>
signup.jsp
<%#page language="java" import="java.sql.*"%>
<%#page import="java.io.*"%>
<%
try
{
ResultSet rs=null;
Class.forName("jdbc.odbc.JdbcOdbcDriver");
Connection con= DriverManager.getConnection("jdbc:oracle:jobsportal","abdus","jbaat");
Statement stmt=con.createStatement();
String fname=request.getParameter("fnametxt");
String lname=request.getParameter("lnametxt");
String usrname=request.getParameter("usrnametxt");
String pswd=request.getParameter("pswdtxt");
String phone=request.getParameter("phonetxt");
stmt.executeUpdate("insert into jobs(fname,lname,username,password,phone) values('"+fname+"','"+lname+"','"+usrname+"','"+pswd+"','"+phone+"'");
rs=stmt.executeQuery("select * from jobs");
%>
<html>
<head><title>Sign up Successful</title>
<link rel="stylesheet" type="text/css" href="default.css">
</head>
Your details</br>
<table border="0">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>User Name</th>
<th>Password</th>
<th>Phone number</th>
</tr>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString("fname")%></td>
<td><%=rs.getString("lname")%></td>
<td><%=rs.getString("username")%></td>
<td><%=rs.getString("password")%></td>
<td><%=rs.getString("phone")%></td>
</tr>
<% rs.close();
}}
catch(ClassNotFoundException e)
{
out.println(e.getMessage());
} %>
</table>
</html>
You're using the JDBC/ODBC driver to connect to an Oracle database. And you used the wrong class name to load it. The correct class name is sun.jdbc.odbc.JdbcOdbcDriver.
The JDBC/ODBC driver is an old, obsolete driver, that has been created years ago when databases didn't have native JDBC drivers yet. If your database is Oracle, use the Oracle JDBC driver, and not the JDBC/ODBC driver. You'll have to use a different URL, described in the Oracle driver's documentation.
The problem may be in your driver name.If an oracle driver is used,you have to specify if it is a oracle thin driver or oci or kprb. For instance,
For Oracle:
Jdbc Driver Name="oracle.jdbc.driver.OracleDriver" (if you have it on your system)
Url format="jdbc:oracle:thin:#hostname:port Number:databaseName"
For Odbc:
Odbc bridge="sun.jdbc.odbc.JdbcOdbcDriver"
Url format="jdbc:odbc:dsn_name"

Waiting message on slow redirection

I have the following code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit">
</form>
The problem is that when I submit the form the redirection to mysite.com takes too long time, 5-10s.
I would like to display a messege "Loading... Please wait" och show an animated image so that I know that something is happening.
How do I do in javascript och ajax?
I don't know if it's possible (but I don't think so) but you could add exit(); after setting the header so the rest of the script isn't executed and sent to the browser. That could reduce the time a bit.
What you could try is to do the redirection with javascript instead of a http header.
<?php if (isset($_POST['submit'])): ?>
<script>
alert('Loading... Please wait');
document.location.href = 'http://mysite.com';
</script>
<?php endif; ?>
5-10 secs to submit the page. First of all try to figure out why it is taking that much time.
ANyways, If you just want to see some message when you press submit button, then simply you can add any div ( with initially hidden ). And on click of submit button you can show this div.
See the sample code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<div id='loadingDIV' style='display: none;'></div>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit" onclick='showLoadingAndSubmit();'>
</form>
function showLoadingAndSubmit(){
document.getElementById ('loadingDIV').innerHTML = 'Form submitting. Please wait...';
document.getElementById ('loadingDIV').style.display = 'block';
return true;
}
you should have something like this
the loading has image GIF moving until the ajax request end and then the loading become hidden
where result has the database result grid search on screen
<tr valign="top">
<td id="results" colspan="8" align="center" width="100%" height="250px">
</td>
</tr>
<tr valign="top" id="loading" style="display:none;">
<td colspan="8" width="100%" align="center">
<img name="loading_image" src="images/loading.gif" border="0" width="214" height="200">
</td>
</tr>
function search(tableEvent){
try
{
document.getElementById('loading').style.display="";
var params = 'formAction=' + document.mainForm.formAction.value;
params += '&tableEvent=' + tableEvent;
params += '&txtActionDivisionDesc=' + document.mainForm.txtActionDivisionDesc.value;
createXmlHttpObject();
sendRequestPost(http_request,'Controller',false,params);
ValidationResult();
}
catch(e)
{
alert(e.message);
}
}
function ValidationResult()
{
try
{
if (http_request.readyState == 4)
{
var errors = http_request.responseText;
errors = errors.replace(/[\n]/g, '');
if (window.ActiveXObject)
{// code for IE
xmlRecords=new ActiveXObject("Microsoft.XMLDOM");
xmlRecords.loadXML(errors);
}
else
{
xmlRecords=document.implementation.createDocument("","",null);
parser=new DOMParser();
xmlRecords=parser.parseFromString(errors,"text/xml");
}
document.getElementById('loading').style.display="none";
document.getElementById('results').innerHTML = errors;
http_request = false;
}
}//end try
catch(e)
{
document.getElementById('results').innerHTML = errors;
return;
}
}

How to retrieve multiple records from Jquery to my RazorView page

I have a button "btnGetAddress" on my razor page .On clik of this button,I am calling a Jquery to get my addressItmes object to be displayed on to my View page.
On clicking "btnGetAddress" I am able to hit my "JsonResult GetAddresses()" and retrieve records within my Jquery (success: function (data)).and this data has multiple address records. But I do not know how to take this data to my view .Please help me to get my data to be displayed on to my View
When my page get loaded,the user will see only the "btnGetAddress" button .When the user click on the btnGetAddress, it will call the Jquery Click function to fetch all address records from database and display each set of records on the page
$("#btnGetAddress").click(function () {
debugger;
var selected = $("#ddlType").val();
if (selected == "")
{ selected = 0; }
var dataToSend = {
SelectedTypeId: selected
};
$.ajax({
type: "GET",
url: '#Url.Action("GetAddresses", "Content")',
data: { SelectedTypeId: selected },
success: function (data) {
debugger;
},
error: function (error) {
var verr = error;
alert(verr);
}
});
pasted below is my JsonResult GetAddresses() which gets called to retrieve addressItems
public JsonResult GetAddresses()
{
model.AddressItems = AddressService.RetrieveAllAddress();
// My AddressItems is of type IEnumerable<AddressItems>
return Json(model.AddressItems, JsonRequestBehavior.AllowGet);
}
Here is my razor View Page where the address records are to be displayed.
........................
<input type="submit" id="btnGetAddress" name="btnSubmit" value="Show Addresses" />
if (!UtilityHelper.IsNullOrEmpty(Model.AddressItems))
{
foreach (var AddressRecord in Model.AddressItems)
{
<fieldset >
<legend style="padding-top: 10px; font-size: small;">Address Queue(#Model.NumRecords)
</legend>
<table>
<tr>
<td>
<span>Index</span>
</td>
<td>
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="X" />
<br />
</td>
</tr>
<tr>
<td>
<span>Address1</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Address )
#Html.ValidationMessageFor(model => AddressRecord.Address)
</td>
</tr>
<tr>
<td>
<span>Description</span>
<br />
</td>
<td>
#Html.EditorFor(model => AddressRecord.Description)
#Html.ValidationMessageFor(model => AddressRecord.Description)
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSave" name="btnSubmit" value="Save" />
</td>
<td>
<input type="submit" id="btnDelete" name="btnSubmit" value="Delete" />
</td>
</tr>
</table>
</fieldset>
}
}
<fieldset>
Or is there any better way to achieve my objective?
Since you are getting the data via ajax you should use a jquery template engine. Basically get the data the way you are and on success you do something like
<script language="javascript" type="text/javascript">
$(function () {
$.getJSON("/getprojects", "", function (data) {
$("#projectsTemplate").tmpl(data).appendTo("#projectsList");
});
});
</script>
<script id="projectsTemplate" type="text/html">
<section>
<header><h2>Projects</h2></header>
<table id="projects">
<th>Name</th>
{{tmpl(items) "#projectRowTemplate"}}
</table>
</section>
</script>
<script id="projectRowTemplate" type="x-jquery-tmpl">
<tr>
<td>${name}</td>
</tr>
</script>
<div id="projectsList"></div>
Now each template engine is different but the above gives you an idea of what you can do
If you want to return JSON object in your controller, you are going have to turn your view into a string and return it as part of the message. If you google there are some methods out there that can do this.
However, I really think that's the hard way, why not take the data you get from the JSON in the controller and put it in a MODEL and then return your VIEW with the model data passed in. I think that's the easier way.

Resources