473,387 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

ajax and js not working together!!

hi,

am very new to ajax and js . i tried using ajax for server validation in my jsp. i also used js for client side validation

i have my js script for client side validation in a seperate file. i embedded the ajax code in the jsp itself.

the client side validation and the ajax code are working when i use them seperately.
but when i try to use them both , the client side validation is not taking place at all. my page is directly dispatched to the validation servlet in the server .

is it a problem to include two seperate js files in a single jsp file?

pls help me out!!
Sep 13 '08 #1
16 2176
acoder
16,027 Expert Mod 8TB
Without code, we can only guess. Show your code or a link to a test page.
Sep 13 '08 #2
this is the jsp page i tried

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3.  
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5.  
  6. <style type="text/css">
  7.  .bp_invalid {
  8.     color:white;
  9.     background:red;
  10.  }
  11.  .bp_valid {
  12.     color:green;
  13.  }
  14. </style>
  15. <script type="text/javascript">
  16.  
  17. function AJAXInteraction(url, callback) {
  18.  
  19.     var req = init();
  20.     req.onreadystatechange = processRequest;
  21.  
  22.     function init() {
  23.       if (window.XMLHttpRequest) {
  24.         return new XMLHttpRequest();
  25.       } else if (window.ActiveXObject) {
  26.         return new ActiveXObject("Microsoft.XMLHTTP");
  27.       }
  28.     }
  29.  
  30.     function processRequest () {
  31.       // readyState of 4 signifies request is complete
  32.       if (req.readyState == 4) {
  33.         // status of 200 signifies sucessful HTTP call
  34.         if (req.status == 200) {
  35.           if (callback) callback(req.responseXML);
  36.         }
  37.       }
  38.     }
  39.  
  40.     this.doGet = function() {
  41.       req.open("GET", url, true);
  42.       req.send(null);
  43.     }
  44. }
  45.  
  46. function validateUserId() {
  47.     var target = document.getElementById("userid");
  48.     var url = "Validate.do?id=" + encodeURIComponent(target.value);    
  49.     var target = document.getElementById("userid");
  50.     var ajax = new AJAXInteraction(url, validateCallback);
  51.     ajax.doGet();
  52. }
  53.  
  54. function validateCallback(responseXML) {
  55.    var msg = responseXML.getElementsByTagName("valid")[0].firstChild.nodeValue;
  56.    if (msg == "false"){
  57.        var mdiv = document.getElementById("userIdMessage");
  58.        // set the style on the div to invalid
  59.        mdiv.className = "bp_invalid";
  60.        mdiv.innerHTML = "Invalid User Id";
  61.        var submitBtn = document.getElementById("submit_btn");
  62.        submitBtn.disabled = true;
  63.     } else {
  64.        var mdiv = document.getElementById("userIdMessage");
  65.        // set the style on the div to valid
  66.        mdiv.className = "bp_valid";
  67.        mdiv.innerHTML = "Valid User Id";
  68.        var submitBtn = document.getElementById("submit_btn");
  69.        submitBtn.disabled = false;
  70.     }  
  71. }
  72. </script>
  73. <SCRIPT TYPE="TEXT/JAVASCIPT" SRC="fun.js"></SCRIPT>
  74.  <title>Form Data Validation using AJAX</title>
  75. </head>
  76.  <body onload="disableSubmitBtn()">
  77.  
  78.  <h1>Form Data Validation using AJAX</h1>
  79.  <hr/>
  80.  
  81.  
  82.  
  83.   <form name="updateAccount" onsubmit="return validateFormOnSubmit(this)" action="Validate.do" method="post" >
  84.    <input type="hidden" name="action" value="create"/>
  85.    <table border="0" cellpadding="5" cellspacing="0">
  86.     <tr>
  87.      <td><b>User Id:</b></td>
  88.      <td>
  89.       <input    type="text"
  90.                 size="20"  
  91.                   id="userid"
  92.                 name="id"
  93.                 autocomplete="off"
  94.                 onblur="validateUserId()">
  95.      </td>
  96.      <td>
  97.       <div id="userIdMessage"></div>
  98.      </td>
  99.     </tr>
  100.     <tr> <td><b>Password:</b></td>
  101.         <td>
  102.             <input type="password"
  103.                    size="20"
  104.  
  105.                    name="Password"
  106.                    autocomplete="off"
  107.                </td> 
  108.     </tr>
  109.  
  110.      <tr> <td><b>Re Enter the Password:</b></td>
  111.         <td>
  112.             <input type="password"
  113.                    size="20"
  114.  
  115.                    name="Password2"
  116.                    autocomplete="off"
  117.                </td> 
  118.     </tr>
  119.     <tr>
  120.      <td align="right" colspan="2">
  121.       <input type="Submit" id="submit_btn" value="submit" >
  122.      </td>
  123.      <td></td>
  124.     </tr>
  125.    </table>
  126.   </form>
  127.  </body>
  128. </html>
the script file i tried is this

fun.js
Expand|Select|Wrap|Line Numbers
  1. function validateFormOnSubmit(theForm) {
  2. var reason = "";
  3. reason += validateUsername(theForm.id);
  4.  reason += validatePassword(theForm.Password,theForm.Password2);
  5.  
  6.  
  7.   if (reason != "") {
  8.     alert("" + reason);
  9.     return false;
  10.   }
  11.  
  12.   return true;
  13. }
  14.  
  15.  
  16. function validateUsername(fld) {
  17.     var error = "";
  18.     var illegalChars = /\W/; // allow letters, numbers, and underscores
  19.  
  20.     if (fld.value == "") {
  21.         fld.style.background = 'Yellow'; 
  22.         error = "Enter a Username !!.\n";
  23.     } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
  24.         fld.style.background = 'Yellow'; 
  25.         error = "The username should be of atleast 5 characters.\n";
  26.     } else if (illegalChars.test(fld.value)) {
  27.         fld.style.background = 'Yellow'; 
  28.         error = "The username contains illegal characters.\n";
  29.     } else {
  30.         fld.style.background = 'White';
  31.     } 
  32.     return error;
  33. }
  34.  
  35.  
  36. function validatePassword(fld2,fld2) {
  37.     var error = "";
  38.     var illegalChars = /[\W_]/; // allow only letters and numbers 
  39.  
  40.     if (fld1.value == "") {
  41.         fld1.style.background = 'Yellow';
  42.         error = "Pls Enter a Password.\n";
  43.     }else if(fld2.value == "") {
  44.         fld2.style.background = 'Yellow';
  45.         error = "Pls Enter the Password again.\n";
  46.         }else if ((fld1.value.length < 6) || (fld1.value.length > 15)) {
  47.         error = "The password should be atleast 6 chars \n";
  48.         fld1.style.background = 'Yellow';
  49.     }else if (illegalChars.test(fld1.value)) {
  50.         error = "The password contains illegal characters.\n";
  51.         fld1.style.background = 'Yellow';
  52.     } else if(fld1.value!=fld2.value)
  53.          error="The password in the two fields must match\n" 
  54.          fld2.style.background="Yellow";
  55.     else {
  56.         fld.style.background = 'White';
  57.     }
  58.    return error;
  59. }   

this is the servlet

Expand|Select|Wrap|Line Numbers
  1. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  2.     throws ServletException, IOException {
  3.  
  4.  
  5.         ResultSet rs;
  6.         String sql;
  7.  
  8.       request.setCharacterEncoding("UTF-8");
  9.  
  10.  
  11.         Statement stmt ;
  12.         String name=request.getParameter("id").toString();
  13.  
  14.  
  15.  
  16.  
  17.  
  18.         try {
  19.             //loading the driver
  20.             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  21.  
  22.             //connection object created using DriverManager class
  23.             //student_base is the name of the database
  24.             Connection connect =DriverManager.getConnection("jdbc:odbc:student_base");
  25.  
  26.  
  27.  
  28.  
  29.             stmt=connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  30.  
  31.             //creating prepared statement object pstm so that query can be sent to database
  32.  
  33.  
  34.  
  35.  
  36.             //execute method to execute the query
  37.             rs= stmt.executeQuery("SELECT PASSWORD FROM STUDENT_BASE"+" WHERE NAMES = '" + name + "'");
  38.  
  39.             RequestDispatcher rd;
  40.             if(rs.next())                                               //username exists
  41.             {
  42.                  response.setContentType("text/xml");
  43.                 response.setHeader("Cache-Control", "no-cache");
  44.                 response.getWriter().write("<valid>false</valid>");
  45.  
  46.                 //forwarding to the corresponding view
  47.             }
  48.  
  49.             else                                                       //code when username does not exist
  50.             {
  51.                  response.setContentType("text/xml");
  52.                 response.setHeader("Cache-Control", "no-cache");
  53.                 response.getWriter().write("<valid>true</valid>");
  54.  
  55.  
  56.             }
  57.  
  58.  
  59.                 rs.close();
  60.  
  61.             connect.close();
  62.  
  63.         } catch(SQLException sqe) {
  64.             System.out.println(sqe.getMessage());
  65.         } catch(ClassNotFoundException cnf) {
  66.             System.out.println("Class not found error");
  67.         }
  68.  
  69.  
  70.     }
  71.  
  72.     /** Handles the HTTP <code>POST</code> method.
  73.      * @param request servlet request
  74.      * @param response servlet response
  75.      */
  76.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  77.     throws ServletException, IOException {
  78.  
  79.         ResultSet rs;
  80.         String sql;
  81.  
  82.         response.setContentType("text/html;charset=UTF-8");
  83.  
  84.  
  85.         Statement stmt ;
  86.         String name=request.getParameter("id").toString();
  87.         String Password=request.getParameter("Password").toString().trim();
  88.  
  89.  
  90.  
  91.  
  92.  
  93.         try {
  94.             //loading the driver
  95.             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  96.  
  97.             //connection object created using DriverManager class
  98.             //student_base is the name of the database
  99.             Connection connect =DriverManager.getConnection("jdbc:odbc:student_base");
  100.  
  101.  
  102.  
  103.  
  104.             stmt=connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  105.  
  106.             //creating prepared statement object pstm so that query can be sent to database
  107.  
  108.  
  109.  
  110.  
  111.             //execute method to execute the query
  112.             rs= stmt.executeQuery("SELECT PASSWORD FROM STUDENT_BASE"+" WHERE NAMES = '" + name + "'");
  113.  
  114.             RequestDispatcher rd;
  115.  
  116.             if(rs.next())                                               //username exists
  117.             {
  118.  
  119.                 //add code to take to the next page
  120.  
  121.  
  122.             }
  123.  
  124.             else {
  125.                 PreparedStatement  pstm=connect.prepareStatement("insert into student_base values(?,?)");
  126.                 pstm.setString(1,name);
  127.                 pstm.setString(2,Password);
  128.                 //execute method to execute the query
  129.                 pstm.executeUpdate();
  130.  
  131.                 rd=request.getRequestDispatcher("success.view");
  132.  
  133.  
  134.  
  135.                 rd.forward(request,response);
  136.                 //closing the prepared statement  and connection object
  137.                 pstm.close();
  138.  
  139.             }
  140.             rs.close();
  141.             connect.close();
  142.  
  143.         } catch(SQLException sqe) {
  144.             System.out.println(sqe.getMessage());
  145.         } catch(ClassNotFoundException cnf) {
  146.             System.out.println("Class not found error");
  147.         }
  148.  
  149.     }
  150.  
  151.  
Sep 14 '08 #3
acoder
16,027 Expert Mod 8TB
On line 73, change
Expand|Select|Wrap|Line Numbers
  1. <SCRIPT TYPE="TEXT/JAVASCIPT" SRC="fun.js"></SCRIPT>
to
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript" src="fun.js"></script>
and see if that makes a difference.
Sep 14 '08 #4
nope !! i tried it!!no diff wotsoever......

pls help me out...i am stuck up with this for more than a day... iam having no bright ideas with my meagre knowledge of ajax and js.....

thanks for the effort though!!
Sep 14 '08 #5
acoder
16,027 Expert Mod 8TB
Do you see any errors when you submit?
Sep 14 '08 #6
the page is loading with a script error.. IE show the message that the page loaded with error... mozilla is showing no errors.... ajax is working alone fine anyway..


also everytime i change the focus from the textbox under question the" page has error" is intimated in the IE... so am not sure whether its a problem because of the ajax or the js .....

i tried including the client side js functions which i now hav in fun.js to the jsp itself along with ajax part.. in that case both of the validations are not working....
Sep 14 '08 #7
acoder
16,027 Expert Mod 8TB
What's the error message?
Sep 14 '08 #8
am talkin abt the error that is shown at the bottom most corner of the page to the left of the status bar in the browser..... it just shows page loaded with error and the alert symbol...no other indication.....my server is not throwing up any exception or anything in the server log...
Sep 14 '08 #9
acoder
16,027 Expert Mod 8TB
In IE, if you double click the icon, you should see the error message and line number. Are you sure there's nothing in the Firefox console?
Sep 14 '08 #10
ya mozilla shows no error....the error in ie is showing an line no which is not a part of the js..it belongs to a code in form tag in jsp
Sep 14 '08 #11
acoder
16,027 Expert Mod 8TB
I notice a few problems in your code. Use something else instead of id for the name because id is already a property of the form and therefore may cause it to behave erratically. Alternatively, use theForm.elements["id"] to refer to the element.

You've not closed the two password fields with the closing angle bracket >

The validatePassword() function has two fld2 as arguments.
Sep 14 '08 #12
i changed them.. . no change in output
Sep 18 '08 #13
acoder
16,027 Expert Mod 8TB
OK, what's the latest version of your code?
Sep 18 '08 #14
basically i made all the changes you suggested.... i tried using the client side validation and ajax validation for the first field in the same function..both are working fine...but if i introduce another function which does client side validation for second field its not taking place.....
Sep 18 '08 #15
acoder
16,027 Expert Mod 8TB
So you mean the username validation works, but the password validation doesn't?
Sep 18 '08 #16
yup .....the client side validation for password is not working...it works if i take away the ajax code
Sep 19 '08 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Sokolov Yura | last post by:
Django Model is wonderfull. But SQLObject more flexible (and powerfull, as i think, and has already more db interfaces). But Django Model is tied with Django, and using Django with another OO...
13
by: David L Wright II | last post by:
Does anyone know when building a msi file under VB.Net 2003, it would try to install something from the VS 2005 Beta 1? I have both products installed. Thanks,
0
by: Rod | last post by:
Well, I've taken the plunge and gotten myself my first domain. (I've worked on other peoples and of course at work, but never done my own domain.) With this new project my family and I will...
4
by: geshan | last post by:
In php5 I am not able to use include funciton and header("location:""" together please help.
8
by: Bill Gower | last post by:
I have a webapp that uses the AjaxControlToolkit. The app and ajax works fine when run within my dev server in Visual Studio 2005 but does not work on IIS. Any Suggestions? Bill
2
by: buddyr | last post by:
Hello, I am having trouble with two combo boxes working together. two tables table1 table2 table1 fields -number and name table 2 fields -code and number ...
4
by: MimiMi | last post by:
I'm trying to put together a http response header. It seems to work, except for that I don't get the data string added correctly! I wouldn't be surprised if my problems have something to do with...
3
by: SavRak | last post by:
Hi, I seem to be having an issue linking my XML document and XML Schema together. Both are not working, and do not seem to be validating when using: http://tools.decisionsoft.com/schemaValidate/ ...
1
by: software4 | last post by:
So I am not great at Javascript, but i have 2 scripts that i want to work with each other. When i use one by itself, they each work fine, but when i add them together it does not work. I have a...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.