Total Pageviews

6/10/2013

Remove HTML Tags from a string




Recently I required to remove HTML tags from html page. For that I have used following function which removes all HTML tags.

Source Code

Paste Your Source code into designated area.For Example.
    
    <p><strong>Input code:</strong>
        (<em>Note: Processing is done on the "input-code" id</em>)</p>
    <pre>
    <code id="input-code">    
    <h2>About</h2>
    <p>Here you will find post about how to remove HTML tag from a string using
    javascript.<p>
    <p><a href="/about">Read more</a></p>

External File

Create RemoveHTML.js external file and paste following code.

         function removeHTMLTagFromString()
         {
             if (document.getElementById && document.getElementById("input-code"))
             {
                  var strHtmlCode = document.getElementById("input-code").innerHTML;

                 /* It replaces escaped brackets with real ones,
                  i.e. < is replaced with < and > is replaced with > */

                  strHtmlCode = strHtmlCode.replace(/&(lt|gt);/g,
                  function(strMatch, p1)
                  {
                     return (p1 == "lt") ? "<" : ">";
                   });
                   var strTagStrippedText = strHtmlCode.replace(/<\/?[^>]+(>|$)/g, "");    

                   alert("Output text:\n" + strTagStrippedText);
            }
         }

Head

import javascript file into head section of HTML document.
    <script type="text/javascript" src="removeHTML.js"></script>

Body

Paste the code into BODY section, which HTML Tag you want to remove in HTML document.
    <p><strong>Input code: </strong>( <em>Note: Processing is done on   the "input-code" id </em>)</p>
    <pre> 
    <code id="input-code"> 
    <h2>About</h2>
    <p>Here you will find post about how to remove HTML tag from a string using
    javascript.<p>
    <p><a href="/about">Read more </a></p>
    </code> 
    </pre>
   
    <a href="#" onclick="removeHTMLTagFromString(); return false;">
    »Click to remove all HTML  tags from the input code </a>.


6/05/2013

Using JQuery, AJAX, JSON and ASP.NET Web Services


We are on era of the web development where more and more websites are loading lots of dynamic content on web pages. In this tutorial, I will show how to use web service and JSON to display dynamic contents on web page. 

Create a new ASP.NET website in the visual studio and add following Product.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Product class objects to the clients.
           public class Product
         {
                   public int Id { get; set; }
                   public string Name { get; set; }
                   public decimal Price { get; set; }
         }
Next, add an ASP.NET web service ProductWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:
          [WebService(Namespace = "http://tempuri.org/")]
       [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
      
       // To allow this Web Service to be called from script, using ASP.NET   
          AJAX,uncomment the following line.
       
       [System.Web.Script.Services.ScriptService]

       public class ProductWebService : System.Web.Services.WebService
       {
           List<Product> list = new List<Product>();
           
           public ProductWebService () 
           {
             //Uncomment the following line if using designed components
             //InitializeComponent();
              list.Add(new Product { Id = 1, Name = "TV", Price = 22000 });
             list.Add(new Product { Id = 2, Name = "Microwave", Price = 24000 });
             list.Add(new Product { Id = 3, Name = "WashingMachine", Price = 28000 });
             list.Add(new Product { Id = 4, Name = "Music Player", Price = 29000 });
             list.Add(new Product { Id = 5, Name = "Food Processor", Price = 19000 });
          
           [WebMethod]
           public List<Product> GetAllProducts()
           { 
             return list;
           }

           [WebMethod]
           public Product GetProductDetails(string productId)
           {
             int prodId = Int32.Parse(productId);
             Product product = list.Single(e => e.Id == prodId);
             return product;
           }
       }
In start, the web service declares a list of Product objects which I will be using to store Product objects for this tutorial. I have added five Product objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.
           List list = new List();
          list.Add(new Product { Id = 1, Name = "TV", Price = 22000 });
      list.Add(new Product { Id = 2, Name = "Microwave", Price = 24000 });
      list.Add(new Product { Id = 3, Name = "WashingMachine", Price = 28000 });
      list.Add(new Product { Id = 4, Name = "Music Player", Price = 29000 });
      list.Add(new Product { Id = 5, Name = "Food Processor", Price = 19000 });

A web method GetAllProducts returns the list of products to the clients.
          [WebMethod]
      public List<Product> GetAllProducts()
      { 
           return list;
      }

Another simple web method GetProductDetails will filter and return a single Product object based on product id.

           [WebMethod]
       public Product GetProductDetails(string productId)
       {
           int prodId = Int32.Parse(productId);
           Product product = list.Single(e => e.Id == prodId);
           return product;
       }

Next add the following code in your web page in HTML source. It has a DropDownList to display all products and an HTML table to display single product details.
 
    <form id="form1" runat="server">
    Select Product:
    <asp:DropDownList ID="DropDownList1" runat="server" Width="150">
        <asp:ListItem Text="Select" Value="-1" />
    </asp:DropDownList>
    <br />
    <br />
    <table style="border: solid 1px black; width: 300px; display: none;
    background-color:#f3f3f3"
        cellpadding="4" cellspacing="0" id="outputTable">
        <tr>
            <td>Product ID:</td>
            <td><span id="spnProductId" /></td>
        </tr>
        <tr>
            <td>Product Name:</td>
            <td><span id="spnProductName" /></td>
        </tr>
        <tr>
            <td>Price:</td>
            <td><span id="spnPrice" /></td>
        </tr>
    </table>
    </form>


Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
    <script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllProducts which is declared just after ready function. This function will call GetAllProducts web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from the DropDownList using JQuery val method and then pass that employee id to another JavaScript function GetProductDetails which will retrieve details of that particular employee by calling web service GetProductDetails method and then will display details in HTML table.

   <script type="text/javascript">

        $(document).ready(function ()

        {
            // Load Products
            GetAllProducts();

            var DropDownList1 = $("#DropDownList1");


            DropDownList1.change(function (e)

            {
                var productId = DropDownList1.val();
                if (productId != -1)
                {
                    // Get Product Details
                    GetProductDetails(productId);
                }
                else
                {
                    $("#outputTable").hide();
                }
            });

        });


        function GetAllProducts()

        {
            var DropDownList1 = $("#DropDownList1");

            $.ajax({

                type: "POST",
                url: "ProductWebService.asmx/GetAllProducts",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response)
                {
                    var Products = response.d;
                    $.each(Products, function (index, Products)
                    {
                        DropDownList1.append('<option value="' + Products.Id + '">' + Products.Name + '</option>');
                    });
                },
                failure: function (msg)
                {
                    alert(msg);
                }
            });
        }

        function GetProductDetails(productId)

        {
            $.ajax({
                type: "POST",
                url: "ProductWebService.asmx/GetProductDetails",
                data: "{'productId':'" + productId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response)
                {
                    var Product = response.d;
                    $("#spnProductId").html(Product.Id);
                    $("#spnProductName").html(Product.Name);
                    $("#spnPrice").html(Product.Price);
                    $("#outputTable").show();
                },
                failure: function (msg)
                {
                    alert(msg);
                }
            });
        }
    
    </script>
      

1. Function : GetAllProducts() In the above function, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the products. I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all products. If you will build and test your page in the browser you will see DropDownList populate with prodcut names as shown in the following figure. You can also see the JSON response in FireBug just below to the DropDownList. 

2. Function : GetProductDetails() The above function required for the GetProductDetails function. The code is almost similar to the GetAllProducts function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing product id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate product as there is only one product to receive from the web service method. Note the Product class properties Id, Name and Price are used to display values inside span elements declared in HTML table above. That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see efficient output.


So thats it you are ready to rock with JSON + Web Service



Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews