Connecting Tech Pros Worldwide Forums | Help | Site Map

ajax and js not working together!!

Newbie
 
Join Date: Sep 2008
Posts: 10
#1: Sep 13 '08
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!!

acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#2: Sep 13 '08

re: ajax and js not working together!!


Without code, we can only guess. Show your code or a link to a test page.
Newbie
 
Join Date: Sep 2008
Posts: 10
#3: Sep 14 '08

re: ajax and js not working together!!


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.  
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#4: Sep 14 '08

re: ajax and js not working together!!


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.
Newbie
 
Join Date: Sep 2008
Posts: 10
#5: Sep 14 '08

re: ajax and js not working together!!


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!!
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#6: Sep 14 '08

re: ajax and js not working together!!


Do you see any errors when you submit?
Newbie
 
Join Date: Sep 2008
Posts: 10
#7: Sep 14 '08

re: ajax and js not working together!!


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....
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#8: Sep 14 '08

re: ajax and js not working together!!


What's the error message?
Newbie
 
Join Date: Sep 2008
Posts: 10
#9: Sep 14 '08

re: ajax and js not working together!!


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...
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#10: Sep 14 '08

re: ajax and js not working together!!


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?
Newbie
 
Join Date: Sep 2008
Posts: 10
#11: Sep 14 '08

re: ajax and js not working together!!


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
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#12: Sep 14 '08

re: ajax and js not working together!!


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.
Newbie
 
Join Date: Sep 2008
Posts: 10
#13: Sep 18 '08

re: ajax and js not working together!!


i changed them.. . no change in output
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#14: Sep 18 '08

re: ajax and js not working together!!


OK, what's the latest version of your code?
Newbie
 
Join Date: Sep 2008
Posts: 10
#15: Sep 18 '08

re: ajax and js not working together!!


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.....
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#16: Sep 18 '08

re: ajax and js not working together!!


So you mean the username validation works, but the password validation doesn't?
Newbie
 
Join Date: Sep 2008
Posts: 10
#17: Sep 19 '08

re: ajax and js not working together!!


yup .....the client side validation for password is not working...it works if i take away the ajax code
Reply