jQuery getJSON() example using Java Servlet

jQuery getJSON() is convinence method for doing AJAX request when the dataType is JSON. Basically it is equivalent to
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
}); 
If you are interested in learning about jQuery.ajax() method or the back-end Java Servlet programming related to this tutorial then click on the link below
jQuery AJAX request and response example - Java Servlets, MySQL and JSON

In this example we have a form that takes a country code and then makes an AJAX request using the getJSON() method to check if the country code exists in our MySQL database. If the country code is valid then we display the related information. In addition to that we learn how to use the error(), beforeSend() and complete() methods associated with JSON request.


jQuery getJSON() example using Java Servlet
jQuery getJSON() Java Servlet response

jQuery Source Code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*" %>    
<!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">
<meta name="robots" content="noindex,nofollow"/>
<title>Programmers sample guide, help is on the way</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function() {

 //Stops the submit request
 $("#myAjaxRequestForm").submit(function(e){
        e.preventDefault();
 });
 
 //checks for the button click event
 $("#myButton").click(function(e){
        
   //get the form data and then serialize that
         dataString = $("#myAjaxRequestForm").serialize();
         
   //getJSON request to the Java Servlet
   $.getJSON("../CountryInfo", dataString, function( data, textStatus, jqXHR) {
           //our country code was correct so we have some information to display
            if(data.success){
             $("#ajaxResponse").html("");
             $("#ajaxResponse").append("<b>Country Code:</b> " + data.countryInfo.code + "<br/>");
             $("#ajaxResponse").append("<b>Country Name:</b> " + data.countryInfo.name + "<br/>");
             $("#ajaxResponse").append("<b>Continent:</b> " + data.countryInfo.continent + "<br/>");
             $("#ajaxResponse").append("<b>Region:</b> " + data.countryInfo.region + "<br/>");
             $("#ajaxResponse").append("<b>Life Expectancy:</b> " + data.countryInfo.lifeExpectancy + "<br/>");
             $("#ajaxResponse").append("<b>GNP:</b> " + data.countryInfo.gnp + "<br/>");
            } 
            //display error message
            else {
                   $("#ajaxResponse").html("<div><b>Country code in Invalid!</b></div>");
               }
          })
    .error(function(jqXHR, textStatus, errorThrown){
      //console.log("Something really bad happened " + textStatus);
       $("#ajaxResponse").html(jqXHR.responseText);
    })
    .beforeSend(function(jqXHR, settings){
     //adding some Dummy data to the request
     settings.data += "&dummyData=whatever";
     //disable the button until we get the response
     $('#myButton').attr("disabled", true);
    })
    .complete(function(jqXHR, textStatus){
     //enable the button 
     $('#myButton').attr("disabled", false);
    });
 
 });

});

</script>
</head>

<body>
<div id="allContent">

<div id="myExample">
 <form id="myAjaxRequestForm">
  <fieldset>
   <legend>jQuery getJSON() example using Java Servlets and MySQL database</legend>
 
    <p>
     <label for="countryCode">Country Code:</label><br />
     <input id="countryCode" type="text" name="countryCode" />
    </p>
    <p>
     <input id="myButton" type="button" value="Submit" />
    </p>
  </fieldset>
 </form>
 <div id="anotherSection">
  <fieldset>
   <legend>Response from jQuery getJSON() Request</legend>
     <div id="ajaxResponse"></div>
  </fieldset>
 </div> 
</div> 
 
</div>       
</body>
</html>

References

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.