Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax call on anchor tag click

I am new to jQuery and trying to learn it example by example In the below example, I am trying to call a servlet on an event of anchor tag click using jQUery Ajax. I have more than one anchor tag in my page and I want a different servlet to be invoked for each of them. If I use the id of anchor tag like $('#submit1').click as in below example it is not working. But, if I replace it with 'a' it is working which invokes the same servlet for both of anchor tags

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls using Jquery in Servlet</title>
        <script src="http://code.jquery.com/jquery-latest.js">   
        </script>
        <script>
            $(document).ready(function() {                        
                $('#submit1').click(function(event) {
                    event.preventDefault();   
                    var username=$('#user').val();
                $.get('ActionServlet',{user:username},function(responseText) { 
                        $('#welcometext').text(responseText);         
                    });
                });
            });

            $(document).ajaxStart(function(){
                $('#content_progress').text("Loading...");
            });

            $(document).ajaxComplete(function(){
                $('#content_progress').text("");
            });

        </script>
</head>
<body>
<form id="form1">
      <h1>AJAX Demo using Jquery in JSP and Servlet</h1>
           Enter your Name:
           <input type="text" id="user"/><br>

           <a name="submit1" href="#">View Profile</a>
           <a name="submit2" href="#">Course Details</a>
           <br/>
</form>
     <div id="content_progress">
     </div>
     <div id="welcometext">
     </div>
</body>
</html>
like image 361
Naveen Kumar Konda Avatar asked Aug 25 '13 06:08

Naveen Kumar Konda


1 Answers

id-selector

change name=submit1

to

id=submit1

<a id="submit1" href="#">View Profile</a>

or

attribute-equals-selector

if you want access by a tag by name

change $('#submit1').click(function(event) {

to

$('a[name="submit1"]').click(function(event) {

like image 183
Tushar Gupta - curioustushar Avatar answered Oct 03 '22 07:10

Tushar Gupta - curioustushar