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 ♣
name = name.replace(/'/g, '♣');
state = state.replace(/'/g, '♣');
//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 ♣ with single quote
Name = Name.Replace("♣", "'");
State = State.Replace("♣", "'");
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