Error in inserting data with JSON and Ajax - asp.net

I don't know where the problem is, my code looks fine and I tried hard, but getting error all the time.
Here is my code:
Markup:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function(){
var Name=document.getElementById('Text1').value
var Class=document.getElementById('Text2').value
var Data=JSON.stringify({Name:Name,Class:Class});
alert(Data);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/InsertData',
data:Data,
async: false,
success: function (response) {
$('#Text1').val('');
$('#Text2').val('');
},
error: function () {
alert("Error")
}
});
});
});
</script>
ASP.NET AJAX Page Method in code-behind:
[WebMethod]
public string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}

Try this:
Method must be static if it is in aspx page code behind
[WebMethod]
public static string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}

You don't need to stringify it.
Without stringifying just pass
"{'Name':'"+Name+"','Class':'"+Class+"'}"
If you want to pass the stringified object it must be as shown below
JSON.stringify({'Name':Name,'Class':Class});
See the Quotes added.
var Data=JSON.stringify({'Name':Name,'Class':Class});
alert(Data);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/InsertData',
data:Data,
async: false,
success: function (response) {
$('#Text1').val('');
$('#Text2').val('');
},
error: function ()
{ alert("Error") }
});
And in the page back code
[WebMethod]
public string InsertData(myobj getdat)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", getdat.Name);
cmd.Parameters.AddWithValue("#Classs",getdat.Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
public class myobj
{
public string Name {get;set;}
public string Class{get;set;}
}

ASP.NET AJAX Page Methods must be static, change your code to this:
[WebMethod]
public static string InsertData(string Name, string Class)
{
SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(#EmpName,#Classs)",con);
cmd.Parameters.AddWithValue("#EmpName", Name);
cmd.Parameters.AddWithValue("#Classs",Class);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
Read Why do ASP.NET AJAX page methods have to be static? for an explanation as to why.

Related

Unknown web method When Making AJAX Call to WebMethod with ASP.NET

I'm kinda new to using AJAX call to a WebMethod. I feel my Web Method logic is but maybe someone could help out here. I do get an unknown web method error when I log the AJAX response to the console. Below is my Web method and AJAX call code.
$("#btnLogin").click(function () {
email = $("#txtEmailAddress").val();
password = $("#txtPassword").val();
//Create the login info object
var loginInfo = {};
//Set the object properties and value
loginInfo.Email = email;
loginInfo.Password = password;
//Make the ajax call
$.ajax({
type: "POST",
dataType: 'json',
url: '<%=ResolveUrl("identicate.aspx/ValidateUsersToken") %>',
data: '{loginInfo:' + JSON.stringify(loginInfo) + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d == null || data.d == undefined)
{
alert("Username or password not correct = " + data.d);
console.log(data);
console.log(loginInfo);
console.log(this.url);
}
},
error: function (data) {
console.log(data);
console.log(loginInfo);
console.log(this.url);
alert(data.d);
}
});
});
And here's my web method
[WebMethod]
public static String ValidateUsersToken(iloginmodel loginInfo)
{
//Variable to hold the user email address
String email = string.Empty;
//Get the connection string from config file
String connectionString = iDbConfiguration.GetConnectionString();
//Create the command text
String commandText = "select Email, Password from VUser where Email = #Email & Password = #Password";
//Create database connection object and open it
using(SqlConnection loginConnection = new SqlConnection(connectionString))
{
//Set command paramters
SqlCommand loginCommand = new SqlCommand(commandText, loginConnection);
//Set command type to text
loginCommand.CommandType = System.Data.CommandType.Text;
//Add parameter to command
loginCommand.Parameters.AddWithValue("Email", loginInfo.Email);
loginCommand.Parameters.AddWithValue("#Password", loginInfo.Password);
//Open the database connection
try
{
loginConnection.Open();
SqlDataReader loginReader = loginCommand.ExecuteReader();
if(loginReader.HasRows)
{
HttpContext.Current.Response.Write(loginReader.ToString());
while (loginReader.Read())
{
if (loginReader.HasRows)
{
email = loginReader["Email"].ToString();
}
}
}
}
catch(SqlException sqlEx)
{
HttpContext.Current.Response.Write(sqlEx.Message);
}
finally
{
loginConnection.Close();
}
}
return email;
}

ASP.NET: Relative Path with Root Operator('~') in Client side

I have implemented a web page with asp.net.
It has some ajax function.
in ajax function, Get a image path from server side webMethod.
The image path consist of root operator, for example "~/Images/Icons/SendEmail.png".
In Client side, I want to set image path to img element.
How can I set the image from this relative path?
Here is my code snippet.
Please refer this and give me some advices. Thank you in advance.
Clien side
function DrawImage() {
$.ajax({
type: 'POST',
url: '../Management/GetImage',
data: '{Index: "' + Index + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (resp) {
if (resp.d == null) {
return;
}
var ImagePath = resp.d;
var image = document.createElement('img');
image.src = ImagePath; // e.g. "~/Images/Image.png"
$(imageDiv).append(image);
},
error: function (msg) {
alert("Failed to Image: " + msg.statustext);
}
});
}
Server Side WebMethod
[WebMethod]
public static string GetImage(string Index)
{
string conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Select_ImagePath";
command.Parameters.AddWithValue("#Index", Index);
string imgPath = "";
try
{
conn.Open();
SqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
imgPath = (string)dataReader["Image_Path"]; // e.g. "~/Images/Image.png"
}
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
return imgPath;
}
I solved this problem by just implementing some function in javascript like below.
function ConvertRelPathToAbsPath(path)
{
var absPath ="";
if (path.length > 0)
absPath = window.location.protocol + '//' + location.host + path.substr(1);
return absPath;
}

Binding Lable from webmethod using ajax

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

Getting [object Object] error when call JQuery Ajax function for Json data

I'm getting the following error when try to read json data from asp.net function, here is the image error
Here is the jQuery code,
<script type="text/javascript">
$(document).ready(function () {
$("#getdata").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
// $("#company").html(data.d);
console.log(data);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
what wrong I did to get this error. Appreciate your any help.
getting this error from console log,console.log(error)
The reason you are seeing that is that data.d is an object representing the returned JSON text response. When you pass in an object into alert, it displays [object Object]. Whatever you are looking for will be a property of data.d. I would put a breakpoint on that line and see what properties are available. It'll be something like data.d.myProperty which will contain the actual string / HTML you are trying to work with.
dont use alert! That will show this only.
Since your response is a Json Object, please try to JSON.stringify it or use console.log to view the data
Finally, I found what was the issue, I have to add "[WebMethod()]" declaration just before the asp.net function. For example,
[WebMethod()]
public static string GetData()
{
try
{
string strjson;
string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionstring);
DataSet DS = new DataSet();
String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=#cmpid";
SqlCommand cmd = new SqlCommand(CmdText, Con);
cmd.Parameters.Add("#cmpid", SqlDbType.Int).Value = 22;
Con.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
DataTable dTable = DS.Tables[0];
strjson = GetJSONString(dTable);
Con.Close();
return strjson;
}
catch (Exception ex)
{
throw new System.Exception("Error In Get Data" + ex.Message);
}
}
This answer not for experts only for just beginners, thank you.

JQuery AutoComplete Source Issue C#

I am trying to get a simple example of how to us the AutoComplete JQuery plug-in work but running into some issue. The code is written in C# (2008) without using MVC.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<head runat="server">
<title></title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
//GetFormulary();
LoadAutoComplete();
});
function LoadAutoComplete() {
$("#quickSearchTextBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/WebSite1/Default.aspx/GetTest2",
data: "{}",
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item.TestName,
value: item.TestName
}
}));
}
});
},
minLength: 2
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="quickSearchTable" border="0">
<tbody>
<tr>
<td>
<input style="width: 100%" id="quickSearchTextBox" title="Enter search words" maxlength="200" value="" />
</td>
</tr>
</tbody>
</table>
<div id="searchResults" style="display: none;">
</div>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetTest1()
{
return GetFTest2("art");
}
private static string GetFTest2(string searchPhrase)
{
var formularyTests = new List<FormularyTest>();
const string connectionString = "";
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
var sqlCommand = new SqlCommand("Search", sqlConnection) { CommandType = CommandType.StoredProcedure };
sqlCommand.Parameters.Add(new SqlParameter("#Phrase", searchPhrase));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
formularyTests.Add(new FormularyTest { Name = sqlDataReader["LongName"].ToString() });
}
}
var jSearializer = new JavaScriptSerializer();
return jSearializer.Serialize(formularyTests);
}
[WebMethod]
public static List<FormularyTest> GetTest2()
{
return GetFTest1("arterial");
}
private static List<FormularyTest> GetFTest1(string searchPhrase)
{
var formularyTests = new List<FormularyTest>();
const string connectionString = "";
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
var sqlCommand = new SqlCommand("Search", sqlConnection) { CommandType = CommandType.StoredProcedure };
sqlCommand.Parameters.Add(new SqlParameter("#Phrase", searchPhrase));
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
formularyTests.Add(new FormularyTest { Name = sqlDataReader["LongName"].ToString() });
}
}
return formularyTests;
}
}
public class FormularyTest
{
public string Name { get; set; }
public string Url { get; set; }
}
For some reason I cannot get anything to show up in the textbox. A little help would be much appreciated.
The JavaScriptSerializer is returning a result in the format of:
{d:"[{\"Name\":\"Test 1\",\"Url\":\"url1\"},{\"Name\":\"Test 2\",\"Url\":\"url2\"}]"}
So, data.d would give you your serialized string [{"Name":"Test 1","Url":"url1"},{"Name":"Test 2","Url":"url2"}]. That woudl be closer to what you want, but you're really after a JSON array version of that string. If you use eval(data.d) instead of data in your success function, it will work. Admittedly, using eval is an imperfect solution, but it does allow your code to "work".
The following JavaScript has the change:
function LoadAutoComplete() {
$("#quickSearchTextBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Service.asmx/Test",
data: "{'searchTerm':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response($.map(eval(data.d), function (item) {
return {
label: item.Name,
value: item.Url
}
}));
},
error: function (result) {
alert("Error loading the data");
}
});
},
minLength: 2
});

Resources