Power Of JSON/jQuery

In this article, you see the real power of jQuery and JSON. I will show you how you can get the values of all the fields on the page in a single line and insert all the fields in a single query dynamically without knowing and writing the table column name.

This article shows you the power of jQuery. As you all know,  jQuery increases the developer's productivity by simplifying the DOM manipulation. DOM defines a standard to access the document. The DOM of the page acts as an interface between the document and the JavaScript. The main advantage of the jQuery is that it is easy to use, and developers can use various types of selectors like ID and class to perform different functions. Let's look at the power of jQuery by using jQuery selector to send all data fields by using two lines of code.

First start from the database structure. Let us make one employee table,
  1. CREATE TABLE [dbo].[Employee_Personal](
  2. [EP_id] [int] IDENTITY(1,1) NOT NULL,
  3. [F_name] [nvarchar](100) NOT NULL,
  4. [M_name] [nvarchar](100) NOT NULL,
  5. [L_name] [nvarchar](100) NOT NULL,
  6. [Age] [int] NOT NULL,
  7. [Email_id] [nvarchar](max) NULL,
  8. CONSTRAINT [PK_Employee_Personal] PRIMARY KEY CLUSTERED
  9. (
  10.    [EP_id] ASC
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  12. ) ON [PRIMARY]
After this, we design our HTML Page. Keep in mind the ID of the textbox is the same as the database field. 
  1. <table style="width: 70%">  
  2.     <tr>  
  3.         <td>  
  4.             <span class="formtxt2">First Name</span><span style="color: Red">*</span>  
  5.         </td>  
  6.         <td>  
  7.             <input type="text" class="form-control mndtry" id="F_name" maxlength="50" />  
  8.         </td>  
  9.         <td>  
  10.             <span class="formtxt2">Middle Name</span><span style="color: Red">*</span>  
  11.         </td>  
  12.         <td>  
  13.             <input type="text" class="form-control mndtry" id="M_name" maxlength="50" />  
  14.         </td>  
  15.         <td>  
  16.             <span class="formtxt2">Last Name</span><span style="color: Red">*</span>  
  17.         </td>  
  18.         <td>  
  19.             <input type="text" class="form-control mndtry" id="L_name" maxlength="50" />  
  20.         </td>  
  21.     </tr>  
  22.     <tr>  
  23.         <td>  
  24.             <span class="formtxt2">Age</span><span style="color: Red">*</span>  
  25.         </td>  
  26.         <td>  
  27.             <input type="text" class="form-control mndtry" id="Age" maxlength="50" />  
  28.         </td>  
  29.         <td>  
  30.             <span class="formtxt2">Email</span><span style="color: Red">*</span>  
  31.         </td>  
  32.         <td>  
  33.             <input type="text" class="form-control mndtry" id="Email_id" maxlength="50" />  
  34.         </td>  
  35.     </tr>  
  36.     <tr>  
  37.     </tr>  
  38.     <tr>  
  39.         <td>  
  40.             <span id="btnsave" class="submit" runat="server" clientidmode="Static" title="Save">Save</span>  
  41.             <span id="btnupd" runat="server" class="submit" clientidmode="Static" title="Save">Update</span>  
  42.             <span id="btnclear" class="submit" runat="server" clientidmode="Static" title="Reset">Reset</span>  
  43.         </td>  
  44.     </tr>  
  45. </table>  
Power Of JSON/jQuery
 
We set up the page, and now we have to get the values of all the text fields using AJAX.
 
In the Insertion method, an object is declared. The object is another data type which is stored in a series of name-value pairs. So here we hold all the input fields and their value in this object. On each of the text fields, we assign a common class form-control. What this class selector does is, it iterates all the text fields having this class name and sets the field ID into the object key and the value into object value.
  1. $(document).ready(function() {  
  2.     $("#<%=btnsave.ClientID%>").click(function() {  
  3.         insertion();  
  4.     });  
  5.     $("#<%=btnclear.ClientID%>").click(function() {  
  6.         clear();  
  7.     });  
  8.   
  9.     function clear() {  
  10.         $('.form-control').val('');  
  11.     }  
  12.   
  13.     function insertion() {  
  14.         var obj = {};  
  15.         $('.form-control').each(function() {  
  16.             var id = $(this).attr('id');  
  17.             obj[id] = $('#' + id).val();  
  18.         });  
  19.         $.ajax({  
  20.             type: "POST",  
  21.             contentType: "application/json; charset=utf-8",  
  22.             url: "employee.aspx/insertion",  
  23.             data: JSON.stringify({  
  24.                 param: obj  
  25.             }),  
  26.             dataType: "json",  
  27.             success: function(response) {  
  28.                 if (response.d === "1") {  
  29.                     alert("Saved Successfully !!!");  
  30.                     clear();  
  31.                 } else if (response.d === "0") {  
  32.                     alert(response.d);  
  33.                 }  
  34.             },  
  35.             error: function(response) {  
  36.                 //                        
  37.             }  
  38.         });  
  39.     }  
  40. });  
Now, this object holds all the page data fields and their values into key-value pairs. See how easy it is now to get all the text fields and their values into an object by using these 2 lines of code only. You can see the power of jQuery -- we don't need to declare each variable again and again. Just iterate the whole page using each loop on the class name only.
 
Now, the next step is to insert this data into the database. For this, we make an AJAX call and send the data by converting the JavaScript object to JSON object using JSON.stringify method. For more information regarding AJAX calls refer to this article:
Web Method For Insertion
  1. [System.Web.Services.WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
  2. public static string insertion(Dictionary < string, string > param) {  
  3.     SqlConnection con = null;  
  4.     string key = "", value = "";  
  5.     con = (SqlConnection) HttpContext.Current.Session["conn"];  
  6.     con.Open();  
  7.     try {  
  8.         foreach(KeyValuePair < string, string > kv in param) {  
  9.             key += kv.Key + ",";  
  10.             value += "\'" + (kv.Value).Split('-')[0] + "\',";  
  11.         }  
  12.         key = key.Substring(0, key.Length - 1); // Remove The Last Comma from the key string  
  13.         value = value.Substring(0, value.Length - 1); // Remove The Last Comma from the value string  
  14.         using(SqlCommand cmd = new SqlCommand()) {  
  15.             cmd.CommandText = "insert into employee(" + key + ") values(" + value + ")";  
  16.             cmd.Connection = con;  
  17.             cmd.Transaction = transact;  
  18.             cmd.ExecuteNonQuery();  
  19.         }  
  20.         con.Close();  
  21.     } catch (Exception ex) {  
  22.         throw ex;  
  23.     } finally {  
  24.         con.Close();  
  25.     }  
  26.     return "1";  
  27. }  
We see how we get all the fields and their value into an object and send it to web method which receives this parameter in a dictionary type. As the name suggests, a dictionary is a collection of words and their definition. Similarly, in  C# a dictionary is a collection of keys and values where a key is like a word and value is like a definition.

Earlier, I suggested that the ID of the field is the same as of the database column -- here is the trick. This dictionary holds the key of textbox ID now, when it iterates my dictionary using foreach loop and cements the key into a string key, it returns the database column separated by commas, which I pass into the query similarly with the fields value, then cement the key values into a string value, and pass this string into the query.

Now, if you have a bunch of columns, just iterate the foreach loop and your query is ready --  no need to pass the column names into the query and then pass their values. Just write two lines of code to get a column in jQuery, and then write two lines of code to run SQL query, and insert all the data of the page into the database  without postback.
 
Readers, jQuery is just like a game -- now it's up to you how you play with it. Keep playing and keep sharing.