I am using the following code for autocompleting search textbox in my website. The code is working fine on localhost but when the site is hosted the "error" box pops up.
Script:
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Index.aspx/GetAutoCompleteData",
data: "{'location':'" + document.getElementById('ContentPlaceHolder1_txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and the function code is:
[WebMethod]
public static List<string> GetAutoCompleteData(string location)
{
List<string> result = new List<string>();
string connect = #"
Data Source=jaipurrooms.db.11458954.hostedresource.com; Initial Catalog=jaipurrooms;
User ID=xyz;
Password=xyz;";
using (SqlConnection con = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Location from Details where Location LIKE '%'+#location+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#location", location);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Location"].ToString());
}
return result;
}
}
}
I think you have to check your url in ajax request. Try to use the following syntax :
url: "./Index.aspx/GetAutoCompleteData",
Related
I cannot get autocomplete to work. I suspect this is because of my declaration of the URL in the Jquery method. How can I fix this issue?
This is the method in the HomeController:
public JsonResult Autocomplete(string term)
{
string connectionString = ConfigurationManager.ConnectionStrings["AbintegroModelContext"].ConnectionString;
List<string> CompanyName = new List<string>();
string query = string.Format("select distinct CompanyName from CompanyTable where CompanyName like '%{0}%'", term);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CompanyName.Add(reader["CompanyName"].ToString());
}
}
}
return Json(CompanyName, JsonRequestBehavior.AllowGet);
}
this is the Index view:
<body>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script>
$(function () {
$("#CompanyName").autocomplete({
source: function (request, response) {
var param = { companyName: $('#CompanyName').val() };
$.ajax({
url: '#Url.Action("Autocomplete", "Home")',
data: JSON.stringify(param),
datatype: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
console.log("Ajax Error!");
}
});
},
minLength: 2 //min legth of textbox input
});
});
</script>
...later on in the same view I have the html helper textbox CompanyName.
#Html.TextBox("CompanyName", null, new { #class = "indexTextbox" })
I haven't tried re-creating this problem on my end.
Have you used your browser's code inspector to see if any errors are returned?
Also you may try placing the jquery code inside a $(document).ready() function to see if that helps.
I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}
In my Ajax function i tried to pass a int Parameter to the Webmethod but it's not success.
Here i paste my code
Ajax Function
$('#drpChurchNames').on('change', function () {
//alert($(this).val());
LoadFathersToChurch(churchId)
});
function LoadFathersToChurch(churchId) {
var url = '<%=ResolveUrl("WebMethods.aspx/GetFatherNames") %>';
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ Id: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
Here is my WebMethod
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<FatherNames> GetFatherNames(int ChurchId)
{
List<FatherNames> FathersList = new List<FatherNames>();
try
{
SqlCommand comChurchNames = new SqlCommand("GetFathers", conDB);
comChurchNames.CommandType = CommandType.StoredProcedure;
comChurchNames.Parameters.Add("#Id", SqlDbType.Int);
comChurchNames.Parameters["#Id"].Value = ChurchId;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comChurchNames.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
FathersList.Add(new FatherNames
{
Id = (int)r["Id"],
FatherName = r["FatherName"].ToString()
});
}
}
Here is my SP
ALTER PROCEDURE [dbo].[GetFathers]
#SelectIndexName int
AS
BEGIN
Select * from dbo.RevFathers
Where ChurchId = #SelectIndexName
END
You are passing Id as parameter and the correct is ChurchId just like webmethod signature GetFatherNames(int ChurchId).
There is the correct way:
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ ChurchId: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
Is your webmethod actually getting executed? If it is and you think it should be returning data, it could be that your webmethod is not returning JSON, thus jQuery may be generating and error and not firing success.
I have this in my global.asax to configure the output for both XML and JSON:
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
Placed in app_start
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
I know this isn't a direct answer, but I can't post comments yet so I would have just asked the above question first about is the webmthod getting called.
I am working on a project that requires to autocomplete textbox when some data is inputted and the data will be fetched from a database.
For this I created a webservice as -
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[ScriptService]
public class SearchIssues : System.Web.Services.WebService
{
//[ScriptMethod]
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
DataSet ds = null;
DataTable dt = null;
OracleConnection conn = null;
StringBuilder sb = new StringBuilder();
try
{
conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["Conn"].ToString());
sb.Append("select issueno from cet_sepcet where issueno like '");
sb.Append(prefixText);
sb.Append("%'");
OracleDataAdapter daRes = new OracleDataAdapter(sb.ToString(), conn);
ds = new DataSet();
daRes.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception exc)
{
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
List<string> IssueList = new List<string>();
for (int i = 0; i < dt.DataSet.Tables[0].Rows.Count; i++)
{
IssueList.Add(dt.DataSet.Tables[0].Rows[i][0].ToString());
}
return IssueList.ToArray();
}
}
The jquery ajax method I wrote is as -
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "SearchIssues.asmx/GetCompletionList",
data: request.term,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item
}
}))
//alert('Hello');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert(errorThrown);
}
});
},
minLength: 1
});
});
The webservice is running perfectly fine. But the problem comes when I try to call the webservice from the .aspx page. Its throws Internal server error.
I am not sure as where I am going wrong. Kindly help.
Thanks in advance.
Akhil
I advice you to use firebug to check whether your Post requests and responses this way you can easily debug your application.
This one in your code of ajax
data: request.term,
Should be actually
data: "{'prefixText':'" + request.term+ "'}",
Your service is expecting prefixText string as a parmeter, I assume request.term is the value.
Update :
I dont know what is not working at your end this works for me :
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.custom.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Service/WSDataService.asmx/GetStatesWithAbbr",
data: "{'name':'" + $(autocomplete).val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.Name,
value: item.Name
}
}))
}
});
},
minLength: 1
});
});
</script>
....
<input id="autocomplete" />
Service :
[WebMethod]
public List<State> GetStatesWithAbbr(string name)
{
List<State> sbStates = new List<State>();
//Add states to the List
}
This code could throw exception, so please verify it one more time, probably table is not retrieved or something like it.
List<string> IssueList = new List<string>();
for (int i = 0; i < dt.DataSet.Tables[0].Rows.Count; i++)
{
IssueList.Add(dt.DataSet.Tables[0].Rows[i][0].ToString());
}
return IssueList.ToArray();
Place this line in your ajax:
data: '{ "prefixText": "' + request.term + '"}',
and it will work exactly as happened with me.
I made this web service that returns a datatable from sql server db. Can someone help me with the jquery to display it?
web service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
DataTable dt = new DataTable();
[WebMethod]
public DataTable dbAccess()
{
using (SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["localConnectionString"]
.ConnectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
conn.Open();
da.SelectCommand =
new SqlCommand("SELECT VehicleMake FROM VehicleMakes", conn);
da.Fill(dt);
}
conn.Close();
}
return dt;
}
}
and this is as far as I got with the jquery
<script type="text/javascript">
$(function () {
$('#Button1').click(getData);
});
function getData() {
$.ajax({
type: "POST",
url: "WebService.asmx/dbAccess",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// What goes here?
},
failure: function (msg) {
//error message
}
});
}
</script>
In the past, when using asmx services with jQuery, I used something like the following for post/json:
Assuming that I had a response class like this:
public ResponseClass
{
public string Message { get; set; }
}
And a webservice with a method like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public ResponseClass PostResponse()
{
var response = new ResponseClass() {Message = "Hello World"};
return response;
}
Some html like this:
<div id="response">
</div>
The javascript:
$.ajax({
url: '/MyService.asmx/PostResponse',
data: "{}",
type: "POST",
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(msg) {
var response = msg.d; //your response object
$('#response').html(response.Message); //set the response div contents to the Message
},
error: function(xhr, status, error) {
alert(error); //do something if there is an error
}
});
Just in case anyone comes by this post looking for the same answer I have provided what I came up with.
My web service communicates with a database, reads a table with a SqlDataReader and loads that data into a datatable. Each row is then stored in an ArrayList.
[WebService(Namespace = "http://babyUnicorns.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public object dbAccess()
{
DataTable table = new DataTable("myTable");
ArrayList arl = new ArrayList();
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString))
{
using(SqlCommand comm = new SqlCommand("SELECT * FROM VehicleMakes",conn))
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
table.Load(reader);
reader.Close();
conn.Close();
}
}
foreach(DataRow dRow in table.Rows)
{
arl.Add(dRow["VehicleMake"]+" "+dRow["VehicleMakeId"]);
}
return arl.ToArray();
}
}
Using jQuery ajax command I take the returned arrayList and foreach item in the array I append to my div named "output". The jQuery $.each command is used to pick apart an array. I figured out how to use it by reading the API.
function getData() {
$.ajax({
type: "POST",
url: "WebService.asmx/dbAccess",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var response = msg.d;
$.each(response, function(index, value) {
$('#output').append(value+'<br />');
});
},
failure: function (msg) {
alert('failure');
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="Button1" value="Get Cars" /><input type="button" id="buttonClear" value="Clear" />
<div id="output">
</div>
</div>
</form>
</body>
</html>
This returns a list of cars pulled from the database.
<input id="Button2" type="button" value="button" onclick="Find()" /><br /> // call the javascript function Find()
//Javascript function Find()
function Find() {
$(document).ready(function () {
$.ajax(
{
type: "POST",
url: "Model/CustomerDTO.asmx/GetDetail",
data: "{'nm':'" + $('#Text1').val() + "'}", // passing a parameter to retrive detail.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = jQuery.parseJSON(msg.d); // parsing of Json string to Javascript object.
alert(obj.COMPANYADDRESS); //. anything(depends upon your Fieldname
$('#RSSContent').html(obj.COMPANYADDRESS); // bind data to a div
},
error: function () {
alert('data could not be be found');
}
});
});
}
You have multiple options
1) You can either return pure html from the back end and do .html on the div tag
2) Construct a jsonp object using stringbuild and return to the UI. In the UI you can use
eval(response) and parse the object.
Let me know if you need any furthur info on this.
I have done both the approaches.
this is form my code , and you can do as below
var jsonobj = eval('(' + tempstr + ')');
for (var i = 0; i < jsonobj.searchsuggest.items.item.length; i++) { }