Retrieve Sql Data Using WebMethod & Jquery - c#

I wants to retrieve data from sql server using webserver/jquery and I read many articles but not getting the require matters except below but I think It's support FrameWork .Net 3.5 not 2.0. And I have the same requirement to use it in ASP.Net 2.0.
//On WebServer Page..
WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class test : System.Web.Services.WebService
{
[WebMethod]
public string GetCustomer(string memberID)
{
string response = "<p>No customer selected</p>";
string connect = "Server=myserver;Initial Catalog=mydatabase;uid=myuser;pwd=mypassword";
string query = "SELECT name, father, mother from samaj where name=#memberID";
if (memberID != null)
{
StringBuilder sb = new StringBuilder();
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("memberID", memberID);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
sb.Append("<p>");
sb.Append("<strong>" + rdr["name"].ToString() + "</strong><br />");
sb.Append(rdr["father"].ToString() + "<br />");
sb.Append(rdr["mother"].ToString() + "<br />");
response = sb.ToString();
}
}
}
}
}
return response;
}
}
}
//.aspx page...
<script type="text/javascript" src="jquery-1.3.2.min.js" ></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#Customers").change(function()
{
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.asmx/GetCustomer",
data: "{ memberID: '" + $('#Customers').val() + "'}",
dataType: "json",
success: function(data)
{
$("#CustomerDetails").html(data.d);
}
});
});
});
</script>
<form id="form1" runat="server">
<div id="SelectCustomers">
<asp:DropDownList ID="Customers" runat="server">
</asp:DropDownList>
</div>
<div id="CustomerDetails">
</div>
</form>
The DropdownList Binding In Default.aspx.cs page...
protected void Page_Load(object sender, EventArgs e)
{
string connect = "Server=myserver;Initial Catalog=mydatabse;uid=myuser;pwd=mypwd
string query = "SELECT name FROM samaj";
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
Customers.DataSource = cmd.ExecuteReader();
Customers.DataValueField = "name";
Customers.DataBind();
}
}
.asmx page testing ok It’s retrieves the data well but on client side It’s not return any data. How to achieve it in ASP.Net 2.0?.

Related

Get data from database without refreshing the page in ASP.NET

I'm doing a project in ASP.net and with SQL Server. I'm calling a stored procedure on user login screen to authenticate the user. But when I call the stored procedure, the entire page needs to be refreshed in order to get the data.
How can I achieve the same without refreshing the page?
This is my current code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
Use Ajax Extension, Here is the quick example:
.aspx File
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" id="username" name="username" placeholder="Enter Username"></asp:TextBox>
<asp:TextBox name="passwd" ID="passwd" runat="server" placeholder="Enter Password"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" />
<br />
<asp:Label ID="LblError" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs File - add this to Click event of Login Button
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "";
SqlConnection cn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
string User = username.Text;
string Pwd = passwd.Text;
//cn = "<< your connection string>>";
try
{
cn.Open();
// Your code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '" + Pwd + "'";
cmd = new SqlCommand(sql, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
catch (Exception exce)
{
LblError.Text = exce.Message;
}
finally
{
cn.Close();
}
}
You can find UpdatePanel and ScriptManager under Toolbox -> Ajax Extension
Use try-catch block to handle runtime exceptions.
Based on the code you have, in Web Forms you can:
use an Update Panel;
or Page/Web Method
or a simple(r) Web handler (ashx)
If you want to load the data without refreshing the page. you can expose webservice method or create page method then you can call ASP.NET page method through ajax
[WebMethod]
public static string Insert_Data(string user, string pwd)
{
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
Client Side
$(document).ready(function () {
$('#btnsubmit').click(function () {
var name = $('#user').val();
var sex = $('#pwd').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Insert_Data',
data: "{'user':'" + user+ "','pwd':'" + pwd + "'}",
async: false,
success: function (response) {
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
});
});
There are 3 possible ways I know of:
1) using update panel:
see example: http://www.aspdotnet-pools.com/2014/07/ajax-login-form-in-aspnet-using-cnet.html
2) using webmethod:
see example: http://www.aspforums.net/Threads/133296/Develop-simple-AJAX-Login-form-using-jQuery-in-ASPNet/
3) using tiered coding:
see example: https://www.codeproject.com/Articles/170882/jQuery-AJAX-and-HttpHandlers-in-ASP-NET
I prefer method 3 coding as it is more flexible and the tiered coding concept is portable to other web programming platform.

Auto Suggestion Search Box in master page not working

I'm attempting to implement an autocomplete search feature in the master page of my project to be used by other pages inheriting the master page but the function returns an error despite there being data in my database table to return. I have checked that the table name, textbox ID and column is correct but I'm still not sure what the problem is. Any help would be appreciated!
This is the script in my master page file:
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#searchTerm").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetmovieTitle",
data: "{'name':'" + document.getElementById('searchTerm').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("No Match");
}
});
}
});
}
</script>
This is the content of my webservice page:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetmovieTitle(string name)
{
List<string> mResult = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\QACinema\\QACinema\\App_Data\\QACinemaHomeCopy.mdf';Integrated Security=True;User Instance=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.CommandText = "Select name from movies where name LIKE '+#name+'%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", name);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
mResult.Add(dr["name"].ToString());
}
return mResult;
}
}
}
}

Inserting records to database using JQuery Ajax call is not working

Friends, I'm new to this jQuery ajax call.
I want to insert data to database without postback.
currently it's working with postback, please find the bug and help.
here i have used jQuery ajax call, in this I'm getting data and
pass it to the webservice for inserting the records in background
without postback but it will get postback and inserting the records.
Here I have used simply three records for testing purposes.
Default.aspx CODE
<head runat="server">
<title></title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnsubmit').click(function () {
var firstname = $('#txtfirstname').val();
var lastname = $('#txtlastname').val();
var occupation = $('#txtoccupation').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/savedata',
data: "{'firstname':'" + firstname + "','lastname':'" + lastname + "','occupation':'" + occupation + "'}",
async: false,
success: function (response) {
$('#txtfirstname').val(''); $('#txtlastname').val(''); $('#txtoccupation').val('');
//alert("Record saved successfully in database");
},
error: function () {
alert("some problem in saving data");
}
});
});
});
</script>
</head>
</html>
Default.aspx.cs CODE
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public static string savedata(string firstname, string lastname, string occupation)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
try
{
SqlCommand cmd = new SqlCommand("Insert into profileinfo values('" + firstname + "','" + lastname + "','" + occupation + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}
catch(Exception ex)
{
return "failed";
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
}
}
Please Try this
Step 1:
Add Name space:
using System.Web.Services;
[WebMethod]
public static string savedata(string firstname, string lastname, string occupation)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
try
{
SqlCommand cmd = new SqlCommand("Insert into profileinfo values('" + firstname + "','" + lastname + "','" + occupation + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}
catch(Exception ex)
{
return "failed";
}
}
in javascript please Try This
$(document).ready(function () {
$('#btnsubmit').click(function () {
var firstname = $('#txtfirstname').val();
var lastname = $('#txtlastname').val();
var occupation = $('#txtoccupation').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/savedata',
data: "{'firstname':'" + firstname + "','lastname':'" + lastname + "','occupation':'" + occupation + "'}",
async: false,
success: function (response) {
$('#txtfirstname').val(''); $('#txtlastname').val(''); $('#txtoccupation').val('');
//alert("Record saved successfully in database");
},
error: function () {
alert("some problem in saving data");
}
});
return false; //Plese return false in your js
});
});
If you are using input button with type="submit" or asp:Button with runat="server" change it to
<input type="button" id="btnsubmit" value="TextHere">
And also change you error function like this it will give you the exact error if any
error: function (err) {
alert(JSON.stringify(err)));
}
And there is no need for this function if you are using ajax
protected void btnsubmit_Click(object sender, EventArgs e)
{
}
Add name space using System.Web.Services;
then add [webmethod] befor your static string function.It will work.

I want to fetch some data from database on click of the link using jquery but on clicking link getting an alert with undefined type

I want to get data from the database based on the text of that link on click of the link but getting undefined alert message.
I'm new to jquery so please help me out with this if anybody can. Thanks in advance.
here is the code snippet
jquery
<script type="text/javascript">
var name;
$(function () {
$("[id*=Menu] td a").click(function () {
name=$(this).text().trim();
GetRecords();
//alert(name);
});
});
function GetRecords() {
$("#loader").show();
$.ajax({
type: "POST",
url: "kioskstore.aspx/GetPrice",
data: '{name: ' + name + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var productsInfo = xml.find("Products_Info");
productsInfo.each(function () {
var customer = $(this);
$(".price").html(customer.find("Products_Price").text().trim());
});
$("#loader").hide();
}
</script>
asp.net
<div style="margin-top:25px;height:40px;float: left;margin-left:40px;font-family:cursive;font-size:24px;color:#ffe476;">
<asp:Label runat="server" CssClass="price" Text=""></asp:Label>
</div>
and the code behind C#
[WebMethod]
public static string GetPrice(string name)
{
return GetPriceData(name).GetXml();
}
public static DataSet GetPriceData(string name)
{
string query = "select * from Product_Info where Product_Name=#pname";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#pname", name);
//cmd.Parameters.Add("#PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
return GetData(cmd);
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Product_Info");
return ds;
}
}
}
}
I think you are missing enclosing quotes for string.
Use
data: '{name: "' + name + '"}'
instead of
data: '{name: ' + name + '}'
Responding to your comment:
That message means you are requesting an incorrect URL. Please try with this.
url:document.location + '/GetPrice'
Please confirm whether your request is going to the correct URL. You can use the network monitor component of a browser development tools or an HTTP proxy like Fiddler. If you have chrome, you can check this using the Network tab of the Development Tools. Additionally you can make use of a chrome plugin called Postman to invoke HTTP request to check if they are working or not.
if you are calling from the same page?

JQUery autocomplete in ASP.Net Webservice

This is driving me crazy , I just keep getting the message "error" nothing else. I had this autocomplete working with AJAX Toolkit, but I want to try JQuery, I have very little experience with JQuery. Here is WebService code:
[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 WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public static string GetNames(string prefixText, int count)
{
Trie ArtistTrie = new Trie();
if (HttpContext.Current.Cache["CustomersTrie"] == null)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand();
comm.CommandText = "SELECT * FROM TopArtists ORDER BY name ASC";
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = comm;
comm.Connection = conn;
conn.Open();
da.Fill(dt);
conn.Close();
Trie newtrie = new Trie();
foreach (DataRow dr in dt.Rows)
{
// topartists.Add(dr[0].ToString());
newtrie.Add(dr[0].ToString());
}
HttpContext.Current.Cache["CustomersTrie"] = newtrie;
}
ArtistTrie = (Trie)HttpContext.Current.Cache["CustomersTrie"];
List<string> list = ArtistTrie.GetCompletionList(prefixText, 10);
List<Band> list1 = new List<Band>();
foreach (string a in list)
{
Band newband = new Band();
newband.Name = a;
list1.Add(newband);
}
string json = JsonConvert.SerializeObject(list1, Formatting.Indented);
return json;
}
Here is JQuery Code:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#tb1").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term ,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
})
</script>
Well for one, your jQuery code has errors, including a missing semicolon at the end and an unnecessary function wrapping the autocomplete, try:
<script type="text/javascript">
$(document).ready(function() {
$("#tb1").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetNames",
data: request.term,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
for the ajax part, the return need to be in array, string[]
sample code,
[WebMethod]
public string[] area(string prefixText)
{
List<string> listString = new List<string>();
using (SqlConnection con = new SqlConnection("Initial Catalog=EMS;Server=S-CEMSDB01;User ID=sa;Password=sqltest"))
{
SqlCommand cm = new SqlCommand("select distinct eqp_location from EQUIPMENT where eqp_location like '" + prefixText + "%' order by eqp_location", con);
con.Open();
SqlDataReader dr = cm.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listString.Add((dr["eqp_location"].ToString()));
//c.FullName, serializer.Serialize(c))
}
}
dr.Close();
dr.Dispose();
con.Close();
}
string[] str = listString.ToArray();
return str;
}

Categories

Resources