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}})
Related
C#,ASP.NET MVC,Ajax:-I have a form page where there is a drop down list showing customers name from database table customers.Based on the customer selection by passing customer id to database table I want to fetch his email id and contact number and display it in form read only text fields.My problem is controller code is not working.In other words i am not able to check whether id is reaching my controller function to fetch data and the query is executing or not.I am getting error function data on form page
My jquery code is as below
CustomerList1 is the id for drop down box
var cusKey to hold customer id
GetCustmrDetails is my controller function to fetch data based on id
$("#CustomerList1").change(function (event) {
var cusKey = $("#CustomerList1").val();
alert("customerKey:" + cusKey);
$.ajax({
type: 'GET',
url: "/CustomerController/GetCustmrDetails/",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ "id": cusKey }),
success: function (data) {
alert("available");
$("#EMailAddress").val(data.EMailAddress);
$('#Phone').val(data.Phone);
},
error: function () {
alert("error");
}
});
});
My controller code is as below
[HttpGet]
public ActionResult GetCustmrDetails(int id)
{
List<CustomerModel> customer = new List<CustomerModel>();
string query = string.Format("Select EMailAddress,Phone From
OC_Customer where CustomerKey="+id);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
customer.Add(new CustomerModel{
EMailAddress = reader["EMailAddress"].ToString(),
Phone = reader["Phone"].ToString()
});
}
}
return Json(customer, JsonRequestBehavior.AllowGet);
}
}
I want email id and contact number to display on form page(cshtml)
please use this one
$("#CustomerList1").change(function (event) {
var cusKey = $(this).val();
alert("customerKey:" + cusKey);
$.ajax({
type: 'GET',
url: "/Customer/GetCustmrDetails?id="+cusKey,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (data) {
alert("available");
$("#EMailAddress").val(data[0].EMailAddress);
$('#Phone').val(data[0].Phone);
},
error: function () {
alert("error");
}
});
});
How to call jquery ajax to c# page there is no response from visual studio tried through break point
first tried with Big one no response from C# side(ProfitCentersNameInsert) function then tried another simple type (apply) function but no response from both methods
just commented the below lines on Ajax
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
JS Code
$(function() {
profit.onRefresh()
$( "#btnAdd" ).click(profit.onClickSave);
});
var profit = {
onRefresh: function(){},
onClickSave: function(){
var ProfitCenterName =$('#txtProfitCenter').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
url: "ProfitCentersScreen.aspx/apply",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
data:'{}',
async: false,
success: function (response) {
alert( response );
alert(ProfitCenterName);
$('#txtProfitCenter').val('');
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
}
};
C# Code
[WebMethod]
public static string ProfitCentersNameInsert(string ProfitCenterName)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.133;User Id=hll; " + "Password=hll;Database=checking_DB;"); //+ "Pooling=true;MaxPoolSize=100;Timeout=20;"
try
{
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("Insert into tbl_Profit_Centers(Profit_Center_Id,Profit_center_Name) Values(default,#ProfitCenterName)", conn);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#ProfitCenterName", ProfitCenterName);
command.ExecuteNonQuery();
conn.Close();
return "Success";
}
catch (Exception ex)
{
return "failure";
}
}
[WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
try This
url: "ProfitCentersScreen.aspx",
data: {ProfitCenterName: ProfitCenterName}
Try below points, it should work :
1) if your page is at root level of project then the url should be like below :
url: "/ProfitCentersScreen.aspx/apply"
OR
url: "../ProfitCentersScreen.aspx/apply"
2) stringify your parameter
data: JSON.stringify({})
3) Finally add this parameter
dataType: "json",
Try using response.d in your success
success: function (response) {
alert(response.d);
alert("Record saved successfully..!!");
},
Here's pseudo code a simple jQuery Ajax call
jQuery:
$("#bntAJax").on('click', function (e) {
$.ajax({
type: "POST",
// your webmethod
url: "AjaxFunction/myFunction.asmx/apply",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall() {
}
e.preventDefault();
});
WebMethod :
[WebMethod]
public string apply()
{
return "Hello";
}
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
When I run this code I get alert saying Error.
My Code:
<script type="text/javascript">
debugger;
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'fname':'" + document.getElementById('txtCategory').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select fname from tblreg where fname LIKE '%'+#CategoryText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#CategoryText", CategoryName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["fname"].ToString());
}
return result;
}
}
}
I want to debug my function GetAutoCompleteData but breakpoint is not fired at all.
What's wrong in this code? Please guide.
I have attached screen shot above.
You need to change the data property's value of you $.ajax() call to correctly reflect the C# method parameter i.e. change this line
data: "{'fname':'" + document.getElementById('txtCategory').value + "'}",
to
data: "{'CategoryName':'" + document.getElementById('txtCategory').value + "'}",
The data property should match the parameter in the signature of the action method.
You need to add [WebMethod] attribute over your method. so your method will look like this
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
....
How to use web method link
Edit 1
In your jQuery where you have written url: "GetAutoCompleteData", you need to specify the class or page name and then method name.
You cann't directly call Method you need to use the class (.aspx page) and then method.
hey I want to use autocomplete jquery in asp.net on a control which is used on a default1.aspx page. My control is searchinput.ascx which is in Registration folder. My ploblem is I have written web method (getmylist) on code file of searchinput control. but that method is never called. can anyone help me
Jquery website
You can find wat you need there for a start.
Also, show your ajax call so that I can try helping on y it is not working.
Your approach of writting a web method and making a ajax call from the jquery auto complete should work out fine otherwise.
Its hard to help you without the code but some common causes could be:
You are not using ClientID value correctly - asp.net controls dont have the same id in the actual mark-up as they do in the designer
your web method has an error in it - you should press f12 to open your web developers toolbar and go to NET tab (in firefox at least) to see if a 500 error code or similar is being returned
Create a web method like the following:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetPatientFirstName(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
string connectionstring = CCMMUtility.GetCacheForWholeApplication();
conn.ConnectionString = connectionstring;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select distinct top(10) PatientFirstname from tblMessage where " +
"PatientFirstname like '%'+ #SearchText + '%' order by PatientFirstname";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}", sdr["PatientFirstname"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
here is the html code :
$(document).ready(function () {
$('[ID$=txtPatientFirstname]').live('keyup.autocomplete', function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Resources/WebService.asmx/GetPatientFirstName") %>',
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) {
},
minLength: 1
});
});
});
This is the working example ......hope this will solve your problem..