Call a web method using jQuery Ajax - asp.net

I want to create an Autocomplete field for a search option. I have tried with following code.
But the web method doesn't fire when the Autocomplete function is execution.
What will be the reason ?
Here is the jQuery function:
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
$.ajax ({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Here is the web method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}

Make sure you hit the webservice function by having breakpoint on your service function. Please change your script to below:
<script type="text/javascript">
$(function () {
$("#<%=tags.ClientID %>").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: " <%=ResolveUrl("~/Services/AutoComplete.asmx/GetFarmersByName") %>",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
response($(data.d, function (item)
{
return
{
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>

Above your service class add [System.Web.Script.Services.ScriptService]
Or you can do this in an asp.net page!
add the static keyword and change the webservice to ASP.NET page!
public static string GetFarmersByName(string name)
For example:
A.aspx:
$.ajax({
type: "POST",
url: "A.aspx/GetSN",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async:false,
success: function (json) {
var msg = JSON.parse(json.d);
sn = msg;
},
failure: function () {
alert("Sorry,there is a error!");
}
});
Then in your A.aspx.cs type in:
[WebMethod]
public static string GetSN()
{
Random RN = new Random();
string year = DateTime.Now.ToString("yy").ToString();
string MonAndDate = DateTime.Now.ToString("MMdd").ToString();
string Hour = DateTime.Now.ToString("HHMMss").ToString() + DateTime.Now.Millisecond.ToString() + RN.Next(100, 900).ToString();
string SerialNumber = year + MonAndDate + Hour;
return JsonConvert.SerializeObject(SerialNumber);
}

Assuming tags as your textbox, set data as { 'name': '" + request.term + "'}
$("#<%=tags.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name': '" + 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);
},
});
},
minLength: 0,
focus: function () {
// prevent value inserted on focus
return false;
},
});
debug on method GetFarmersByName,
NOTE: Check have you uncomment [System.Web.Script.Services.ScriptService] on .asmx page.

Post again!!!
Test.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(function(){
$("#Button1").bind("click",function(){
$.ajax({
type: "POST",
url: "Test.asmx/GetFarmersByName",
data:"{'aaa':'zhangsan'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function (json) {
},
failure: function () {
alert("Sorry,there is a error!");
}
});
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>
</body>
</html>
Test.asmx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace TestWebForm
{
/// <summary>
/// Summary description for Test
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 Test : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
}
}

Paste this method inside code behind file where you are calling this method. Change url to url: "Test.aspx/GetFarmersByName" and then test it. Its much clean code rather then Web Service.
using System.Web.Script.Services;
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}

try this -
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
var obj = JSON.Stringfy("{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}");
$.ajax ({
type: "POST",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
and the webmethod-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}

Related

Select2 webforms not binding after returned result with ajax "no results found"

I am returning the result for the researched item or items as json from the back end but the select2 can't seem to append it.
there is no console errors.
here's my code if enyone can help! thanks.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetResults(string q)
{
List<Select2Model> list = new List<Select2Model>();
//geting the data to be searched into a list
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
list = list.Where(x => x.text.ToLower().StartsWith(q.ToLower())).ToList();
}
return new JavaScriptSerializer().Serialize(new { items = list });
}
and here is my front-end code
$("#<%=DDL_NAME.ClientID%>").select2({
//placeholder: "Search for item",
minimumInputLength: 3,
ajax: {
type: "POST",
url: '<%= ResolveUrl("~/page.aspx/GetResults") %>',
dataType: 'json',
data: function (params) {
return JSON.stringify({ q: params.term });
},
contentType: "application/json; charset=utf-8",
dataType: "json",
processResults: function (data) {
return { results: data.items };
}
}
});
I found a solution For those who are searching for this error:
server side:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetResults(string q)
{
List<Select2Model> list = new List<Select2Model>();
//geting the data to be searched into a list
list = (from DataRow row in _cotalog.Rows
select new Select2Model
{
id = row["CODE"].ToString(),
text = row["LABEL"].ToString()
}).ToList();
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
list = list.Where(x => x.text.ToLower().Contains(q.ToLower())).ToList();
}
return new JavaScriptSerializer().Serialize(new { results = list, pagination = new { more = true } }); ;
}
Client Side:
$("#<%=DDL.ClientID%>").select2({
placeholder: "Search for item",
minimumInputLength: 3,
ajax:
{
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("~/page.aspx/GetResults") %>',
data: function (params) {
return JSON.stringify({ q: params.term });
},
processResults: function (data, page) {
//console.log(JSON.parse(data.d).results);
return { results: JSON.parse(data.d).results };
}
}
});
In case you also want the model:
public class Select2Model
{
public string id { get; set; }
public string text { get; set; }
}

formdata in ajax call

When I pass formdata in ajax call after json return it does not return on Success or error block just printing value on browser
// And my Controller side code is
[HttpPost]
public JsonResult Create(InquiryModel model)
{
var inquiry = _inquiryService.GetInquiryById(model.Id);
return Json(inquiry.Id, JsonRequestBehavior.AllowGet);
}
// View side
var formData = new FormData();
jQuery.each(jQuery('#QuotationDocument')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
contentType: false,
processData: false,
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});
when I pass only formData it works fine
Try like this;
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
datatype: "json",
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});

asp.net web forms [WebMethod]

I have a problem with my [WebMethod] when I return Json data List<Contract> from DB using Entity Framework
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "/Pages/App/Docs.aspx/PopulateDataByJquery",
data: "{pageNo: " + pageIndex + ", noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
This my WeMethod.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Contract> PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
return data;
}
I every time getting ajax error, help me please! I don't know how it fix.
You have to make some changes to your ajax call and WebMethod
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "Docs.aspx/PopulateDataByJquery",
data: "{pageNo: pageIndex, noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
Change your WebMethod
[WebMethod]
public static string PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
JavaScriptSerializer TheSerializer = new JavaScriptSerializer()
var TheJson = TheSerializer.Serialize(data);
// for this you need to add using System.Web.Script.Serialization;
return TheJson;
}
For more read this

Unknown web method in asp.net

In the below code I have a textbox .My aim is when I focus on textbox it will call the server side code through ajax.But I got a error unknown web method txtField_GotFocus parameter name method name.Please help me to rectify the error.
design code:
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
//alert("success message here if you want to debug");
},
error: function (xhr) {
var rawHTML = xhr.responseText;
var strBegin = "<" + "title>";
var strEnd = "</" + "title>";
var index1 = rawHTML.indexOf(strBegin);
var index2 = rawHTML.indexOf(strEnd);
if (index2 > index1) {
var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
alert("error: " + msg);
} else {
alert("General error, check connection");
}
}
});
});
});
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged" ClientIDMode="Static"></asp:TextBox>
field.ascx:
public static void txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
}
You are missing [WebMethod] annotation. Also i have modified your code
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];//oops i got my super data
//code...
return "awesome, it works!";
}
Check this Article
Your refactored ajax code
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg);//awesome, it works!
},
error: function (xhr) {
}
});
});
});
Data returned form Server is stored in msg.d field. If you return a single value, you should get it using msg.d. If you return a JSON serialized object you have to parse it using JSON.parse(msg.d)
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg.d);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

Using Ajax in a .net project to call a .aspx.cs function NOT WORKING

Im using Ajax in a .net project (isn't MVC.net). I want to call a function of my .aspx.cs from a JScript Function.
This is my JScript code:
$("a#showQuickSearch").click(function () {
if ($("#quick_search_controls").is(":hidden")) {
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{showQuickSearch}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
}
});
$("#quick_search_controls").slideDown("slow");
$("#search_controls").hide();
$("#search").hide();
} else {
$("#quick_search_controls").hide();
}
});
And this is my .aspx.cs Function:
[WebMethod]
public string SetInfo(string strChangeSession)
{
Label1.Text = strChangeSession;
return "This is a test";
}
The problem is that my .aspx.cs function is not being called and isn't updating the label.text.
Try making your function static.
[WebMethod]
public static string SetInfo(string strChangeSession)
{
//Label1.Text = strChangeSession; this wont work
return "This is a test";
}
data: "{showQuickSearch}" is not valid JSON.
Here's how a valid JSON would look like:
data: JSON.stringify({ strChangeSession: 'showQuickSearch' })
Also your PageMethod needs to be static:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "This is a test";
}
which obviously means that you cannot access any page elements such as labels and stuff. It is inside your success callback that you could now use the result of the PageMethod to update some label or whatever.
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{'strChangeSession':'showQuickSearch'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
error: function (xhr, status, error) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message);
}
});
And your backend code:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "Response ";
}

Resources