473,698 Members | 2,451 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ajax and js not working together!!

10 New Member
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 2196
acoder
16,027 Recognized Expert Moderator MVP
Without code, we can only guess. Show your code or a link to a test page.
Sep 13 '08 #2
ashwinkumar18
10 New Member
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 Recognized Expert Moderator MVP
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
ashwinkumar18
10 New Member
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 Recognized Expert Moderator MVP
Do you see any errors when you submit?
Sep 14 '08 #6
ashwinkumar18
10 New Member
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 Recognized Expert Moderator MVP
What's the error message?
Sep 14 '08 #8
ashwinkumar18
10 New Member
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 Recognized Expert Moderator MVP
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

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

Similar topics

0
1147
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 mapping is not comfortable. Why do not working together? I can't understand. If you (Django and SQLObject) would, you'll beat everyone else in efficiency (i mean ROR and maybe some Python's frameworks). It is for all of Open Source. There a lot of...
13
1303
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
1089
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 likely work on it together. And we'll be using FrontPage 2003. I would also like to use Visual Studio 2005 for those portions when appropriate (such as a members' only area), so I would like to know how to make FP 2003 and Visual Studio 2005 work...
4
10418
by: geshan | last post by:
In php5 I am not able to use include funciton and header("location:""" together please help.
8
4337
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
2381
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 data in table one field number 1,2,3 data in table one field name Tom, Bob, Jim data in table two field code 11,22,33,44,55,66, data in table two field number 1,2,3,1,2,3
4
3084
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 my still existing confusion over arrays and pointers in C since I'm still a newbie, but anyhow, here's the code: #include <time.h> #include <stdio.h> #define WEBBUF_SIZE 32768
3
1926
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/ Im not sure if what I have will work, or does work, as I can still output the XML via an XSLT fine :S Ive attached my XML page and XML Schema, if someone could have a look I would be very grateful! Thanks,
1
1488
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 user form with a bunch of fields on it. If they choose an option on the drop down menu, some fields either show or disappear. Those fields have an "On Change" event that subtracts one field form another and gives us a total....
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8608
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9029
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8867
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6522
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.