Skip to main content

Posts

Showing posts from 2012

Using Ajax to Query MySQL

Using Ajax to Query MySQL Creating the MySQL Table: CREATE TABLE `ajax_example` ( `name` varchar(50) NOT NULL, `age` int(11) NOT NULL, `sex` varchar(1) NOT NULL, `wpm` int(11) NOT NULL, PRIMARY KEY (`name`) ); Inserting Data into the Table: INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20); INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44); INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87); INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72); INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0); INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90); Client Side HTML File (ajax.html): <!DOCTYPE html> <html> <head> <title>Ajax Example</title> <script> function ajaxFunction() { var ajaxRequest; try { ajaxRequest = new XMLHttpRequest(); } catch (e)...

Using JavaScript Image Map

JavaScript can be used to create client-side image maps, which are defined using the <map> and <area> tags in conjunction with the usemap attribute of the <img /> tag. The <map> element acts as a container for defining clickable hotspots within an image. Each <area> tag specifies a shape and coordinates for the hotspot. Below is an example demonstrating how to use an image map with JavaScript to display different messages when hovering over specific areas of an image: <html> <head> <title>Using JavaScript Image Map</title> <script type="text/javascript"> function showTutorial(name) { document.myform.stage.value = name; } </script> </head> <body> <form name="myform"> <input type="text" name="stage" size="20" /> </form> <img src=...

Page Redirection Examples - Learn How to Redirect Web Pages

Page redirection is essential for directing users from one URL to another. Learn how to implement different types of redirects using JavaScript: Why Use Page Redirection? Migrating to a new domain without losing traffic. Routing users based on browser types or geographical locations. Maintaining SEO when restructuring URLs. Examples of Page Redirection Example 1: Instant Redirection Redirect users immediately: <script type="text/javascript"> window.location = "http://www.newlocation.com"; </script> Example 2: Delayed Redirection with Message Display a message and redirect after a delay: <script type="text/javascript"> function Redirect() { window.location = "http://www.newlocation.com"; } document.write("Redirecting in 10 seconds..."); setTimeout('Redirect()...

Printing Web Pages with JavaScript - Learn How to Implement Print Functionality

Implementing printing functionality on web pages using JavaScript's window.print() function allows users to print the current page directly from the browser. Implementing Print Functionality To enable printing, simply use a button with an onclick event: <input type="button" value="Print" onclick="window.print()" /> This button, when clicked, triggers the browser's print dialog. Making a Page Printer-Friendly A printer-friendly page is optimized for printing, usually with minimal graphics and ads: Create a separate printer-friendly version of the page without unnecessary elements. Alternatively, mark printable content with HTML comments like <!-- PRINT STARTS HERE --> and <!-- PRINT ENDS HERE --> , and use server-side scripts to generate a printable version. Our site follows these practices to provide a better printing e...

Client-Side Form Validation with JavaScript

In traditional web forms, validation occurred on the server after submission, leading to delays and server load. JavaScript allows for client-side form validation, checking data before it's sent to the server. Basic Form Validation Basic validation ensures required fields are filled and formats are correct: <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return validate()"> <input type="text" name="Name" /> <input type="text" name="EMail" /> <input type="text" name="Zip" /> <select name="Country"> <option value="-1" selected>[choose yours]</option> <option value="1">USA</option> <option value="2">UK</option> <option value="3">INDIA</option> </select> <input type="submit" val...

Types of Errors and Error Handling in JavaScript

Errors in programming can be categorized into three types: Syntax Errors, Runtime Errors, and Logical Errors. Syntax Errors Syntax errors, also known as parsing errors, occur during compilation or interpretation: <script type="text/javascript"> window.print(; // Syntax error: missing closing parenthesis </script> When a syntax error occurs in JavaScript, only the affected thread stops, allowing other threads to continue. Runtime Errors Runtime errors, or exceptions, occur during script execution: <script type="text/javascript"> window.printme(); // Runtime error: calling a non-existing function </script> Exceptions affect the thread they occur in, but other JavaScript threads can continue normally. Logical Errors Logical errors are mistakes in the logic of your script, resulting in unexpected behavior: These errors are not sy...

Understanding the Difference Between GET and POST Methods in HTTP

GET vs POST Methods in HTTP Understanding GET and POST Methods in HTTP When it comes to web development, understanding the fundamental differences between the GET and POST methods in HTTP is essential. These methods are used to send data between the client and server, but they do so in distinct ways, each with its own advantages and limitations. Let's delve into the key differences between GET and POST methods. GET Method: Data Transmission: In the GET method, data is appended to the URL as query parameters. This makes it easily visible in the browser's address bar. Single Call System: GET requests are simple and involve a single call to the server. Data Size Limit: The amount of data that can be sent via GET is limited to around 256 characters due to URL length restrictions. Speed: Data transmission is generally faster with GET reque...

Setting Up Gzip Compression for Better Web Performance

Setting Up Gzip Compression for Better Web Performance Compression is a simple, effective way to save bandwidth and speed up your site. I hesitated when recommending gzip compression for speeding up your JavaScript due to problems in older browsers. But it's the 21st century. Most of my traffic comes from modern browsers, and quite frankly, most of my users are fairly tech-savvy. I don't want to slow everyone else down because somebody is chugging along on IE 4.0 on Windows 95. Google and Yahoo use gzip compression. A modern browser is needed to enjoy modern web content and modern web speed — so gzip encoding it is. Here's how to set it up. Wait, wait, wait: Why are we doing this? Before we start, I should explain what content encoding is. When you request a file like http://www.yahoo.com/index.html , your browser talks to a web server. The conversation goes a little like this: ...

Servlet Lifecycle Overview

Servlet Lifecycle Overview Servlet Lifecycle Overview The life cycle of a servlet can be categorized into four parts: Loading and Instantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the <load-on-startup> attribute in the web.xml file. If <load-on-startup> has a positive value, the servlet is loaded with the container; otherwise, it loads when the first request is made. After loading, the container creates instances of the servlet. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to it. The init() method must be called before the servlet can service any requests. Initialization parameters persist until the servlet is destroyed. The init() method is called only once t...

Overview of Servlet Methods

Servlet Methods Overview Overview of Servlet Methods A Generic servlet contains the following five methods: init() public void init(ServletConfig config) throws ServletException The init() method is called only once by the servlet container throughout the life of a servlet. This method allows the servlet to initialize and be placed into service. The servlet cannot be put into service if: The init() method does not return within a fixed time set by the web server. It throws a ServletException. Parameters: The init() method takes a ServletConfig object containing initialization parameters and servlet configuration and throws a ServletException if an exception occurs. service() public void service(ServletRequest req, ServletResponse res) throws ServletExceptio...

Servlet Containers Explained

Servlet Containers Explained A servlet container is a compiled, executable program responsible for loading, initializing, and executing servlets. It serves as the official Reference Implementation for Java Servlet and JavaServer Pages technologies. Developed by Sun under the Java Community Process, servlets provide a powerful, platform-independent method for server-side programming, overcoming the limitations of CGI programs. The container handles a large number of requests and can hold many active servlets, listeners, and other components. Notably, the container and its objects are multithreaded, meaning each object must be thread-safe as multiple requests may be handled simultaneously. Note: A servlet container can operate standalone, without a web server, or on a different host. Types of Servlet Containers Servlet containers can be catego...

Understanding Servlets

Understanding Servlets Servlets are server-side components that provide a powerful mechanism for developing server-side programs. They offer component-based, platform-independent methods for building web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent. Benefits of Using Servlets This flexibility allows developers to select a "best of breed" strategy for their servers, platforms, and tools. By using servlets, web developers can create fast and efficient server-side applications that can run on any servlet-enabled web server. Since servlets run entirely inside the Java Virtual Machine (JVM), they are not dependent on browser compatibility. Servlets can access the entire family of Java APIs, includi...

Converting HTML Tables to jqGrid

Converting HTML Tables to jqGrid jqGrid is an excellent jQuery plugin for displaying data in a grid format. One of its useful features is the ability to convert HTML tables into jqGrid, which allows for enhanced user experience and additional functionality. Calling Convention To use the tableToGrid function, ensure that you mark the "Table to Grid" option when you download the grid. The calling convention for the function is: tableToGrid(selector, options) Note: This is a function, not a method. The parameters are: selector (string): Can be either the table's class or id. options (array): An array with grid options. HTML Table Structure The HTML table should have the following structure: <table class="mytab...

Persisting jqGrid State with Cookies

Persisting jqGrid State with Cookies jqGrid is an excellent jQuery plugin for displaying a grid. To enhance user experience, we added some filter possibilities and used jQuery to update the URL where data was fetched from. However, when users navigated away from the grid and returned, it would reset to its start position, losing any filtering or sorting they had set. To solve this, we needed to store the user's selections. Here are two JavaScript functions that achieve this using cookies: function saveGridToCookie(name, grid) { var gridInfo = new Object(); name = name + window.location.pathname; gridInfo.url = grid.jqGrid('getGridParam', 'url'); gridInfo.sortname = grid.jqGrid('getGridParam', 'sortname'); gridInfo.sortorder = grid.jqGrid('getGridParam', 'sortorder'); gridInfo.selrow = grid.jqGrid('getGridParam', 'selro...

Handling Row Selection in jqGrid with jQuery

Handling Row Selection in jqGrid with jQuery The example below specifies the action to take when a row is selected in a jqGrid: var lastSel; jQuery("#gridid").jqGrid({ ... onSelectRow: function(id) { if(id && id !== lastSel) { jQuery('#gridid').restoreRow(lastSel); lastSel = id; } jQuery('#gridid').editRow(id, true); }, ... }); Explanation This script sets up a jqGrid with a custom action for when a row is selected. Here’s a step-by-step explanation: var lastSel; : A variable to store the last selected row ID. jQuery("#gridid").jqGrid({ ... }); : Initializes the jqGrid on the element with ID gridid . onSelectRow: function(id) { ... } : Defines a function to execute when a row is selected. ...

Advanced Usage of $(document).ready() in jQuery

Advanced Usage of $(document).ready() in jQuery One more great thing about $(document).ready() that I didn't mention in my previous tutorial is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your JavaScript file with them. It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain-free. Using Multiple $(document).ready() You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready() . So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so: <script src="/scripts/jquery.js"><...

Understanding $(document).ready() in jQuery

Understanding $(document).ready() in jQuery To ensure an event works on your page, use the $(document).ready() function. This function loads everything inside it as soon as the DOM is ready, before the page contents are fully loaded. Basic Usage Here's how to use the $(document).ready() function to ensure your jQuery code runs when the document is ready: $(document).ready(function() { // put all your jQuery code here }); Advantages of $(document).ready() The $(document).ready() function has several advantages: Separation of Concerns: Keep your JavaScript/jQuery code in a separate file for better maintainability. Inline JavaScript Avoidance: Avoid adding "behavioral" markup in the HTML, which keeps the HTML cleaner. Multiple Functions: Unlike t...

JQGrid Custom Validation - How to Check If Email ID Already Exists in jqGrid

How to Check If Email ID Already Exists in jqGrid Validating whether an email ID already exists is a common requirement in web development. In this guide, we'll show you how to implement this validation in a jqGrid using a custom function. Step 1: Define the Grid Column First, define the column for the email ID in your jqGrid. Add the custom validation rule and specify the custom function: colModel: [ { name: 'emailId', index: 'emailId', width: 200, editable: true, sorttype: 'int', editrules: { email: true, required: true, custom: true, custom_func: checkvalid } } ] Step 2: Implement the Custom Validation Function Next, implement the checkvalid function to check if the email ID already ex...

Create a Dynamic Image Carousel with jQuery and jCarousel

Create a Dynamic Image Carousel with jQuery and jCarousel An image carousel is a great way to showcase multiple images in a small space. In this guide, we'll walk you through creating a dynamic image carousel using jQuery and jCarousel. Step 1: Set Up Your HTML First, create a new HTML file and set up the basic structure: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Carousel</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src=...

Creating Tabs with jQuery: A Step-by-Step Guide

How to Create Interactive Tabs with jQuery Tabs are a fantastic way to organize content on your website, making it more user-friendly and engaging. In this guide, we’ll walk you through creating tabs using jQuery, with clear steps and explanations. Step 1: Set Up Your HTML Structure Create a new HTML file and use the following code to set up the basic structure for your tabs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tabs</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="script/jquery.tabs.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#div-1').tabs(); }); <...

jQuery Drop-Down Menu Example

jQuery Drop-Down Menu Example Have you ever created the drop-down menu using jQuery? No, let's create a simple drop-down menu using jQuery: Step 1: Create the HTML File Create a new file named suckerfish.html and add the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Learn how to create a simple drop-down menu using jQuery. This guide includes a concise code example and clear explanations."> <meta name="keywords" content="jQuery, drop-down menu, JavaScript, web development"> <title>jQuery Drop-Down Menu Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js...

How to Create a Toggle Effect for a Div with jQuery

jQuery Toggle Effect Example This guide demonstrates how to use jQuery to create a simple toggle effect. The example includes a button to show or hide a div and a link inside the div to close it. Code Example Here’s a straightforward example of how to use jQuery for toggling a div: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Learn how to create a simple toggle effect with jQuery. This guide includes a concise code example and clear explanations."> <meta name="keywords" content="jQuery, toggle, JavaScript, web development"> <title>jQuery Toggle Effect Example</title> <script src="https://co...

jQuery Sliding Effects: slideDown, slideToggle, and slideUp

jQuery Sliding Effects: slideDown, slideToggle, and slideUp jQuery provides several methods for creating sliding effects on your web elements. These methods include .slideDown() , .slideToggle() , and .slideUp() . Each of these methods allows you to animate elements with a sliding effect, enhancing the user experience on your website. .slideDown() The .slideDown() method displays the matched elements with a sliding effect. It is used to reveal hidden content with a smooth animation. Example: $('#clickme').click(function() { $('#imageNew').slideDown('slow', function() { // Animation complete. }); }); .slideToggle() The .slideToggle() method is used to either display or hide the matched element with a sliding effect. It toggles the visibility of the element, showing it if it is...

How to Add Horizontal Scrollbar and Checkboxes in jqGrid

Adding Horizontal Scrollbar and Checkboxes in jqGrid jqGrid is a powerful jQuery plugin for creating interactive tables. This guide will show you how to add a horizontal scrollbar and enable checkboxes for row selection in jqGrid. Adding a Horizontal Scrollbar To enable horizontal scrolling in jqGrid, you need to: Set a Fixed Width: Define a fixed width for the grid container. Disable Automatic Resizing: Use shrinkToFit: false to prevent automatic column resizing. Enabling Checkboxes for Multi-Selection To add checkboxes for row selection, follow these steps: Include a Checkbox Column: Use formatter: 'checkbox' in the column model. Enable Multi-Select: Set multiselect: true to allow multiple row selections. ...

Handling Change Events in jqGrid

Handling Change Events in jqGrid In this tutorial, we'll explore how to handle the change event in jqGrid to dynamically update another column based on the selected value. This approach is useful when you need to update related data based on user selections. Example Scenario Let's say we have a jqGrid table with two columns: Country and State. When the user selects a country, the State column should dynamically update to show the relevant states for the selected country. Implementation We'll use the dataEvents option in the colModel configuration to handle the change event. HTML Structure First, let's set up our basic HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>H...

Passing User Input to the Server with jQuery AJAX

Passing User Input to the Server with jQuery AJAX Many times, you collect input from the user and pass that input to the server for further processing. jQuery AJAX makes it easy to pass collected data to the server using the data parameter of any available Ajax method. Example This example demonstrates how to pass user input to a web server script, which sends the same result back, and we print it: <html> <head> <title>AJAX Input Example</title> <script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#driver").click(function(event){ var name = $("#name").val(); $("#stage").load(...

Handling JSON Responses with jQuery's getJSON()

Handling JSON Responses with jQuery's getJSON() There are situations where a server returns a JSON string in response to your request. The jQuery utility function getJSON() parses the returned JSON string and makes it available to a callback function, which is the first parameter of the function. Syntax Here is the simple syntax for the getJSON() method: [selector]. getJSON(URL, [data], [callback]); Here is the description of all the parameters: URL: The URL of the server-side resource contacted via the GET method. data: An object whose properties serve as the name/value pairs used to construct a query string to be...

Loading Data with jQuery AJAX

Loading Data with jQuery AJAX Using jQuery AJAX to load static or dynamic data is very easy. jQuery provides the load() method to accomplish this task efficiently. Syntax Here is the simple syntax for the load() method: [selector]. load(URL, [data], [callback]); Here is the description of all the parameters: URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database. data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. I...

jQuery Hello World example

Hello World jQuery Application In this section, we will create our first jQuery application called "Hello World jQuery". This application will simply display Hello World !! (display due to jQuery) message in the browser. After completing this example, you will be able to include the jQuery library in your application and use it to perform simple functions. Let's start developing the Hello World application in jQuery. Setting up jQuery Click on the following link to open a page containing the jQuery library script. This file is around 70KB. Save this as "jquery-1.4.2.js". Now we are ready to use jQuery inside your HTML page. Hello World Example (HelloWorld.html) <htm...

How To Make Jquery Ajax Call

Beginner's Guide to AJAX Calls in JavaScript Welcome to my first blog post! When I started working on web development, I needed to call a web service in an HTML page to display data. After searching for examples online, I couldn't find a simple, beginner-friendly guide to get started with AJAX. So, I created one myself. I hope this helps you as well! Making an AJAX Call Here's a straightforward example of an AJAX call using jQuery: $.ajax({ type: "POST", url: "test.htm", data: "param1=value1&param2=value2", success: function() { // Code to execute after the AJAX call succeeds }, error: function() { // Code to execute after the AJAX call fails } }); Understanding the AJAX Call Let's break down the code: type:...