Ajax Call not working with asp.net - c#

Ajax Call not working. When I click on btnsubmit, it first shows alert hi and then "Record Save to Database" but data not saving to database. The stored procedure name is "Ajax".
How to solve the error? Thanks in advance..
Procedure is:
create procedure Ajax
#EmpID nvarchar(50),
#EmpName nvarchar(50),
#EmpAddress nvarchar(50)
as
begin
insert into NewEmp (EmpID, EmpName, EmpAddress)
values (#EmpID, #EmpName, #EmpAddress)
end
HTMl Page:
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
var EmpID = $('#TxtID').val();
var EmpName = $('#TxtName').val();
var EmpAddress = $('#TxtAdd').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default11.aspx/InserData",
data: "{'EmpID':'" +EmpID + "','EmpName':'" + EmpName + "','EmpAddress':'" + EmpAddress + "'}",
dataType: "json",
success: function (response) {
alert("Hi");
$("#TxtID").val(''); $("#TxtName").val(''); $("#TxtAdd").val('');
alert("Record Save to Databse");
},
error: function () {
alert("Error");
}
});
});
});
</script>
<div>
<asp:TextBox ID="TxtID" runat="server" ></asp:TextBox>
<br />
EmpName:-<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
<br />
Addresss:-<asp:TextBox ID="TxtAdd" runat="server"></asp:TextBox>
<br />
<input type="button" id="btnsubmit" value="Submit" />
</div>
C# Code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
public partial class Default11 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static bool InserData(string EmpID, string EmpName, string EmpAddress)
{
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["AjaxInsert"].ConnectionString);
try {
SqlCommand cmd = new SqlCommand("Ajax",scon);
scon.Open();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText = "Ajax";
cmd.Parameters.AddWithValue("#EmpID", EmpID);
cmd.Parameters.AddWithValue("#EmpName", EmpName);
cmd.Parameters.AddWithValue("#EmpAddress", EmpAddress);
cmd.Connection = scon;
cmd.ExecuteNonQuery();
scon.Close();
// return "success";
}
catch(Exception ex)
{
// return"error";
}
return true;
}
}

You are use asp control for get input values from user. so make changes in jQuery code as given below. because i was also face same problems. So i hope it would help to you.
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
var EmpID = $('#<%=TxtID.ClientID%>').val();
var EmpName = $('#<%=TxtName.ClientID%>').val();
var EmpAddress = $('#<%=TxtAdd.ClientID%>').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default11.aspx/InserData",
data: "{'EmpID':'" +EmpID + "','EmpName':'" + EmpName + "','EmpAddress':'" + EmpAddress + "'}",
dataType: "json",
success: function (response) {
alert("Hi");
$('#<%=TxtID.ClientID%>').val('');
$('#<%=TxtName.ClientID%>').val('');
$('#<%=TxtAdd.ClientID%>').val('');
alert("Record Save to Database");
},
error: function () {
alert("Error");
}
});
});
});
</script>

Have you checked via breakpoints the string the following command.
"{'EmpID':'" +EmpID + "','EmpName':'" + EmpName + "','EmpAddress':'" + EmpAddress + "'}"
returns to server?
Why not data: { EmpID: EmpID , EmpName: EmpName , EmpAddress: EmpAddress } ?

you cant use asp controls in java scritpt .becase asp controls can be accessable at out side i.e server side only .insted of server contols use html controls like below
EmpID:-
EmpName:-
Addresss:-

Related

Check duplicate value in the database

Before I save value from TextBox into the database I need to check if that value already exists in the database.
This is the TextBox code:
<tr>
<td>
<asp:Label ID="lblProductConstruction" runat="server" Text="Product Construction:" Font-Names="Open Sans"></asp:Label></td>
<td>
<asp:TextBox ID="txtProductConstruction" runat="server" Font-Names="Merriweather" margin-Left="100px" ></asp:TextBox><br />
</td>
</tr>
<tr>
Save button:
<input type="button" class="button" id="myButton" value="Save"/>
Ajax on button click:
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
});
});
WebMethod that takes the value and sends that parameter(#LvlName) to the database:
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
//string strMsg = "";
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdProc = new SqlCommand("InsertLvlName", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("#LvlName", lvl);
cmdProc.ExecuteNonQuery();
//strMsg = "Saved successfully.";
}
catch
{
}
finally
{
connection.Close();
}
return;
}
I need help to check two things:
1) To see if textbox is empty, and if this is the case then don't save the value to the database and show alert that this field needs to have some kind of a value.
2) I need some kind of a check if the same value of a field is already in the database then don't save it.
Thanks in advance !
This is the Simple Validation We can do using jquery
if (inp.val().length > 0) {
//do something
}
else
{
alert("Enter Value")
}
Full Example:-
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
if(lvl.length>0)
{
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else
{
alert("Please enter Value")
}
});
});
Second Part:-
SqlCommand checkvalue = new SqlCommand("SELECT COUNT(*) FROM [TableName] WHERE ([ColumnNameUser] = #user)" , connection);
checkvalue.Parameters.AddWithValue("#user", lvl);
int UserExist = (int)checkvalue.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}
Reference Link
If you Want Sp to check then:-
Edit it based on your name and field names.
CREATE PROCEDURE InsertName
(
#username varchar(25),
#userpassword varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM MyTable WHERE username = #username)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into MyTable(username, userpassword) VALUES(#username, #userpassword)
END
First you will want to probably use jQuery to check if your textbox is empty and if it is then do not fire off the call to the webmethod. See Accessing Asp.net controls using jquery (all options) for calling asp.net controls from jQuery
if ($('#<%= myTextBox.ClientID %>').val().length == 0)
{
alert("Text Box is empty");
}
else
{
///make ajax call to webmethod...
}
Side note what do u want to happen if the user enters a space in the textbox?
Next you could either make a call to insert or update the record in the db so as to not insert any duplicates. Or I would probably want to select all data from the db and then comparing the data to see if the entry from the textbox already exists in the db.
This answer here should be helpful c# update if record exists else insert new record
Something like this should give you the result you need:
SqlCommand cmdCount = new SqlCommand("SELECT * from Table WHERE TextboxValue= #textBoxValue", myConnection);
cmdCount.Parameters.AddWithValue("#textBoxValue", _textBoxValue);
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
///Run Insert statement
}

Trying to pass data through jquery ajax facing issue

I am trying to pass data through jquery ajax but facing issue. I am getting data in the json format
data:'{user: ' + JSON.stringify(user)+'}'
like this
user = {Tdcno: "tw5", Revision: "0", Revision_Date: "22/11/2017", P_Group: "Chain Link", Prod_Desc: "GI wire for chain link", …}
but after processing at this step it directly goes to failure.Any help would appreciated for resolving.
<script type="text/javascript">
$(function () {
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var user = {};
user.Tdcno = $("[id*=Tdc_No]").val();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
c# code
[WebMethod]
[ScriptMethod]
public void SaveFrmDetails(User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TDC_PRODUCT1 VALUES(#Tdc_No, #Revision,#Revision_Date,#P_Group,#Prod_Desc,#N_I_Prd_Std,#Appln,#Frm_Supp,#Created_Date,#Created_By)"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Never manually create json strings. It is error prone and more work than serializing them with JSON.stringify.
'{user: ' + JSON.stringify(user) + '}' produces invalid json because the property user is not properly quoted
Stringify the whole data object
data: JSON.stringify({user:user}})

Issue with passing hiddenfield value

I am trying to pass HiddenField value to WebMethod GetAutoCompleteData to enable auto complete in text box based on selected search field.
I have tried pass HiddenField values using code-behind, but it didn't work.
There is no issues with javascript codes.
Note: I have tried to use HiddenField value in another method, and it worked, so I am sure that HiddenField is taking values using JavaScript code.
Code-behind:
public static string hdnvalue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
hdnvalue = hdnSearchParam.Value;
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value)
{
string hiddenfiedlvalue = hdnvalue;
List<string> result = new List<string>();
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("select #hiddenfiedlvalue from Users where #hiddenfiedlvalue LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", value);
cmd.Parameters.AddWithValue("#hiddenfiedlvalue", hiddenfiedlvalue);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}", hiddenfiedlvalue));
}
return result;
}
}
}
Code used to pass selected values from drop-down menu to HiddenField:
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var param = $(this).attr("href").replace("#", "");
var concept = $(this).text();
$('.search-panel span#search_concept').text(concept);
$('[id$=hdnSearchParam]').val(param);
});
});
</script>
Auto complete code:
<script type="text/javascript">
$(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'value':'" + $('#txtSearch').val() + "'}",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
}
else {
response([{ label: 'No Records Found', val: -1 }]);
}
},
error: function (result) {
alert("Error");
}
});
},
});
}
</script>
ASPX:
<asp:HiddenField ID="hdnSearchParam" runat="server" />
<div class="col-xs-8">
<div class="input-group">
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">Filter by</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>User ID</li>
<li>User Type</li>
<li>User Name</li>
<li>First Name</li>
<li>Last Name</li>
<li>Email</li>
</ul>
</div>
<input type="hidden" name="search_param" value="all" id="search_param">
<asp:TextBox ID="txtSearch" CssClass="autosuggest form-control" runat="server"></asp:TextBox>
<span class="input-group-btn"></span>
</div>
</div>
Your page has several issues.
First, why are you using a hidden field for this? Why don't you just pass the dropdown value as a second parameter in the Ajax request?
Second, in your code behind you are reading the hidden value only on page load, and that value is never updated with each Ajax request (Page_Load is not executed again). You made that static trick with hdnvalue just to make it compile, but it won't work. Also, making it static makes it be shared among all web clients using that page!
Third, why are you storing the dropdown value in its href as well? You could use a span or even simple text instead.
Fourth, you are using the server controls markup ID instead of the ClientID, which may be different depending on the .NET framework you are using. Better play safe and use ClientID always.
Fifth, if with jQuery you select by ID, just use the ID, there's no need to use any other class selectors. Of course, you should never have repeated IDs!
Sixth, you can't use parameterized variables as column names. You must use a dynamic query. More info about that here. Also the reader wasn't working properly (only adding the hidden field) and it's better to enclose the ExecuteReader in a using block.
Summarizing, use this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value, string filterBy)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
con.Open();
string command = string.Format("select {0} from Users where {0} LIKE '%'+#SearchText+'%'", filterBy);
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#SearchText", value);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<string> result = new List<string>();
while (dr.Read())
{
result.Add(dr.GetString(0));
}
return result;
}
}
}
}
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var concept = $(this).text();
$('#search_concept').text(concept);
});
});
</script>
Important: if you are afraid of SQL Injection, you may want to do some validation with filterBy first.
In your Javascript, fix this line only:
data: "{'value':'" + $('#<%= txtSearch.ClientID %>').val() + "','filterBy':'" + $('#search_concept').text() + "'}",
Finally, just get rid of both hidden fields (user control and html control).
try to change data parameter to this:
data: "{'value':'" + $('#hdnSearchParam').val() + "'}",
Try removing the dollar sign from this line of code.
$('[id$=hdnSearchParam]').val(param);
It should be smthing like this:
$('[ID="hdnSearchParam"]').val(param);

Tag System in Asp.net

I want to create a tagging system for my website which allows user to enter the required skills,separated by comma, using ASP.net and C#.
In detail:
A textbox will receive tags, separated by comma.
Suggestions will be provided while typing, based on AVAILABLE tags in my database.
Suggested tags will be displayed, below the textbox.
If a new tag is encountered, it is inserted into database.
The tags (separated by comma), given by the user could be further manipulated according to my needs (a way of doing that).
I want to make a separate entry for each and every tag into the database.
I tried using Tag-it by Levy Carneiro Jr.. it is working perfect for local source.
But when I tried attaching it with my database using this. It just doesn't work.
My code:-
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "tag.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('singleFieldTags2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
<script>
$(function () {
//Local sample- //var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python', 'c', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
$('#singleFieldTags2').tagit({
});
});
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox name="tags" id="singleFieldTags2" value="Apple, Orange" class="autosuggest" runat="server"></asp:TextBox>
</form>
Backend C# code-
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=ZESTER-PC;Initial Catalog=mystp;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select tag_name from tags where tag_name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["tag_name"].ToString());
}
return result;
}
}
}
Here tags is my tag table containing tag_id and tag_name.
I have created the Tagging System using ASP.net
Check it out.. nd do rate it..
Tagging System using ASP.net by Sumanyu Soniwal

How can I correctly format my Web Service to return data from SQL to jQuery autocomplete?

I've been all over Google, attempting one example after another for both AJAX and jQuery AutoComplete.
I've decided on using jQuery's script to render the autocomplete method on my page and I'm using a web service to collect data from my SQL Ce data base.
Here is the error message I receive from jquery and I'm pretty sure that it derives from my webs service... Marr is short for Marriott, the search term I begin to type..
{"Message":"#SearchText : Marr - Input string was not in a correct format.","StackTrace":" at System.Data.SqlServerCe.SqlCeCommand.FillParameterDataBindings(Boolean verifyValue)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteReader()\r\n at GetClients.GetClientNames(String prefix) in c:\Users\CRH-DEV\Desktop\Dev Projects\HelpDesk\App_Code\GetClients.cs:line 42","ExceptionType":"System.FormatException"}
The error derives from line 42 of my webservice's .cs but I'm not quite sure what I'm looking at. I'm guessing the data is not correctly formatted.
The example I am using derives from this website...
Implement jQuery Autocomplete using Web Service in ASP.Net
Here is my complete webservice...
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.Script.Services;
using System.Data.SqlServerCe;
/// <summary>
/// Summary description for Service_CS
/// </summary>
[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 GetClients : System.Web.Services.WebService
{
public GetClients()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetClientNames(string prefix)
{
List<string> customers = new List<string>();
using (SqlCeConnection conn = new SqlCeConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlCeCommand cmd = new SqlCeCommand())
{
cmd.CommandText = "SELECT [Name], [ID] FROM [Current] WHERE " +
"[Name] LIKE #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlCeDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["Name"], sdr["ID"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
}
My aspx Page..(head)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jqueryui.css" rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#<%=ClientSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/GetClients.asmx/GetClientNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfClientID.ClientID %>").val(i.item.val);
},
minLength: 1
});
});
</script>
aspx (body)..
<h1>jQuery Autocomplete Lab</h1>
<asp:TextBox ID="ClientSearch" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfClientID" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick = "Submit" />
If needing, I can post additional code but I think the issue is with my webservice.
I would highly appreciate any feedback on this issue. I think the webservices have been whats killing my on all of the examples I've tried.
Kind Regards,
-Cody
You need to return JSON from you Webservice
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(YourArray);
also change the return type of you webservice function to string
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetClientNames(string prefix)
{
//YOUR CODE
}

Categories

Resources