Handle single quote in Javascript

Download demo project
A better way to handle single Quote in javascript while calling webmethod.
Example
Javascript

 function SaveDetails()
        {
            var name = $("#txtName").val().trim();
            var state = $("#txtState").val().trim();

            //JSON.stringify handle the single quote
            var dataList = JSON.stringify({ Name: name, State: state });

            $.ajax({
                type: "post",
                contentType: "application/json; charset=utf-8",
                url: "login.aspx/SaveDetails",
                data: dataList,
                dataType: "json",
                success: function (data, textStatus) {
                    if (data.d == "true") {
                        alert("success");

                    } else {
                        alert("failed");
                    }
                }
            });
        }

webmethod

 [WebMethod]
        [ScriptMethod]
        public static string SaveDetails(string Name,string State)
        {
            try
            {
                return "true";
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Reference taken from here

500 Internal Server Error while calling webmethod from javascript

To sole this problem in a better way please refere my new blog Handle single quote in Javascript

Please down load the project
This is the error due to single quote in your input parameter

I am going to explain this issue with an example:
there are two input fields in my page

1. Name
2. State

Case1 :
put any value except single quote in both the fields and submit. it will work fine.

Case2 :
put single quote in name field and in state field put any value. Open firebug console and check
result:500 Internal Server Error

Problem : The single quote is creating problem.

Solution:Replace all the single quote in the value with a ♣ and in webmethod again  replace all the ♣ with single quote.

login.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="CallAjaxWebmethod.login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function SaveDetails()
        {
            var name = $("#txtName").val().trim();
            var state = $("#txtState").val().trim();

            //replacing all the single quotes with &clubs;
            name = name.replace(/'/g, '&clubs;');
            state = state.replace(/'/g, '&clubs;');

            //This is the data i am sending to webmethod
            var dataList = "{ 'Name':'" + name + "','State':'" + state + "'}";

            $.ajax({
                type: "post",
                contentType: "application/json; charset=utf-8",
                url: "login.aspx/SaveDetails",
                data: dataList,
                dataType: "json",
                success: function (data, textStatus) {
                    if (data.d == "true") {
                        alert("success");

                    } else {
                        alert("failed");
                    }
                }
            });
        }
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 100%;">
            <tr>
                <td><span>Name</span></td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td><span>State</span></td>
                <td><input id="txtState" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2"><input id="btnSubmit" type="button" value="Save" onclick="SaveDetails()"/></td>
            </tr>
        </table>

    </div>
    </form>

</body>
</html>

login.aspx.cs

using System;
using System.Web.Script.Services;
using System.Web.Services;

namespace CallAjaxWebmethod
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        [ScriptMethod]
        public static string SaveDetails(string Name,string State)
        {
            try
            {
                //i am replacing the &clubs; with single quote
                Name = Name.Replace("&clubs;", "'");
                State = State.Replace("&clubs;", "'");

                return "true";
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}

To sole this problem in a better way please refere my new blog Handle single quote in Javascript

A simple demo Jqgrid

The jqgrid is filled by Ajax enabled webservice.
Steps:
–Add an ASP.NET Web Application. Automatically a project will be added.
–Add a new Web Form to this project and name this page as “gridcontainer.aspx”
–Add A new project and select WCF Service Application to the existing solution. And name this as MyService.
–Add a new WCF Service(Ajax-enabled) service to Myservice project. Automatically it will add a new service having name as Service2.svc
–Add a Global.asax file to this service.
Here is the total project A simple demo Jqgrid
Please download the project and run the Database scripts in for the table and the procedure.
Please insert some records into the table yourself

Service2.svc.cs content:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace MyService
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public string GetName()
        {
            // Add your operation implementation here
            return "Sibasis";
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            DataTable table = new DataTable("Company");
            SqlConnection con=null;
            List lstCo = new List();

            try
            {
                using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["sibasis"].ConnectionString))
                {
                    con.Open();
                    using ( SqlCommand cmd = new SqlCommand("GetAllCompany", con))
                    {
                        using ( SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                        {
                            adapter.Fill(table);
                        }
                    }
                }

                foreach (DataRow row in table.Rows)
                {
                    Company cmp = new Company();
                    cmp.Id = Convert.ToInt32(row["ID"]);
                    cmp.Name = Convert.ToString(row["Name"]);
                    cmp.Country = Convert.ToString(row["Country"]);
                    cmp.State = Convert.ToString(row["State"]);
                    cmp.Language = Convert.ToString(row["Language"]);

                    lstCo.Add(cmp);
                }
        }
            catch (Exception ex)
            {
                throw ex;
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

Add the following codes to the Global.asax file in the Myservice project.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Add the following code in the Myservice web.config file

 <endpointBehaviors>
        <behavior name="MyService.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

Then you are ready with the Jqgrid.

Reload Jqgrid on button click

Reload Jqgrid

Call this function on the button click.

Javascript code:
Note:Replace tbSubscriptionGrid with your own Jqgrid id

function ReloadGrid()
{
$("#tbSubscriptionGrid").jqGrid("setGridParam", { datatype: "json" })
 .trigger("reloadGrid", [{ current: true }]);
}

Html code for button:

<input id="btnReload" onclick="ReloadGrid()" type="button" value="button" />

Reference this link for any more information:JqGrid don’i reload after click on the button

Fill JqGrid using Ajax enabled web service.

You can get the project hereindex
If you want to see a demo the go here trirand.com.
Then click on the Searching tab >Toolbar with Operations

This is pretty simple to fill a jqgrid.
1.Create a simple Project with ASP.NET Web application.
2.Add a WCF Service Application to this solution.
3.Make a slightly modification to your web.config in the wcfservice project

   <endpointBehaviors>
        <behavior name="WcfService1.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

4.Add an Web Service(Ajax enabled) in the wcfservice project.
Service2.svc
content goes here

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            // Add your operation implementation here
            List lstCo = new List();
            for (int i = 0; i < 20; i++)
            {
                Company cmp= new  Company();
                cmp.Id=1;
                cmp.Name="test";
                cmp.Country = "test";
                cmp.State = "test";
                cmp.Language = "test";
                lstCo.Add(cmp);
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

2. Add a Global.asax file.
add the following code to Global.asax file

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Then you are ready to go