Internal Error on jQuery Autocomplete ajax call to ASP.NET - c#

For some reason I am getting an Internal Error (500) when I am attempting to get a List of strings from an ASP.NET method. I have tried many different ways of writing it and an entire page of google is all purple but to no avail. Perhaps maybe you guys can spot something I am completely missing.
Here is the HTML/Javascript
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="messaging.aspx.cs" Inherits="xxx.messaging" %>
<asp:Content ID="Content1" ContentPlaceHolderID="content" runat="server">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function () {
//$(".selectable").selectable();
$('[id$="username_textbox"]').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Services.asmx/getFollowingUsernames",
dataFilter: function (data) { return data; },
data: "{'prefixText': '" + request.term + "' }",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (xhr, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText + " : " + xhr.status;
if (xhr.status != "0" || errorThrown != "abort") {
alert(errorMessage);
}
}
});
},
search: function (event, ui) {
$('.spinner').show();
},
response: function (event, ui) {
$('.spinner').hide();
},
minLength: 1
});
});
</script>
<div class="messaging_wrapper">
<div class="conversations_list" runat="server">
<asp:Button ID="new_message" runat="server" Text="New Message" />
<ol id="conversation_ol" class="selectable" runat="server">
</ol>
</div>
<div id="conversation_wrapper" class="converation_div" runat="server">
<div id="conversation_head">
<asp:TextBox ID="username_textbox" runat="server"></asp:TextBox>
<img src="images/ajax-loader.gif" style="display:none" class="spinner" />
</div>
</div>
</div>
</asp:Content>
Here is the WebService code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace xx.App_Code
{
[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 Services : System.Web.Services.WebService
{
[WebMethod]
public List<string> getFollowingUsernames(string prefixText)
{
SessionAdapter sa = new SessionAdapter();
int id = sa.getUserID();
MembershipAdapter ma = new MembershipAdapter();
List<int> ids = new List<int>();
ids = ma.getUserFollowingList(id);
List<string> usernames = new List<string>();
foreach (int userID in ids)
{
usernames.Add(ma.getUserName(userID.ToString()));
}
return usernames;
}
}
}
Here is what the internal error is:

Seems kind of obvious now, but the line
// [System.Web.Script.Services.ScriptService]
should be un-commented
[System.Web.Script.Services.ScriptService]

Related

C# JSON AJAX returning page HTML instead of method value

NOTE: I did search the forums but didn't find anything that matched my issue or worked.
Hi all,
I'm trying to make a simple call from an asp.net web form using json & ajax to a method in the code-behind page but it's returning that page html instead of the value from the method.
Here is the method in the code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
namespace Tags
{
public partial class AJAX3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string CalculateSum(Int32 Num1, Int32 Num2)
{
Int32 Result = Num1 + Num2;
return Result.ToString();
}
}
}
Here is my web form:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AJAX3.aspx.cs" Inherits="Tags.AJAX3" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call asp.net server side page methods using jQuery AJAX & json</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCalculate").click(function () {
//Get values from textboxes that will be passed to function
var num1 = $('#txtFirstNumber').val();
var num2 = $('#txtSecondNumber').val();
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
//Url is the path of our web method (Page name/function name)
url: "AJAX3/CalculateSum",
//Pass values to parameters. If function have no parameters, then we need to use data: "{ }",
data: "{'Num1':'" + num1 + "', 'Num2':'" + num2 + "'}",
//called on ajax call success
success: function (result) {
$('#dvMsg').text("Sum of " + num1 + " and " + num2 + " = " + result);
},
//called on ajax call failure
error: function (xhr, textStatus, error) {
$('#dvMsg').text("Error:" + error + ", xhr: " + xhr + ", textStatus: " + textStatus);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Enter First Number:</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server" Text="22" /></td>
</tr>
<tr>
<td>Enter Second Number:</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server" Text="33" /></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnCalculate" Text="Calculate" runat="server" OnClientClick="return false;" />
<div id="dvMsg"></div>
</td>
</tr>
</table>
</div>
</form>
</body>
My goal is to return a string and not a JSON object.
What am I doing wrong?
Thanks!

How to make jquery autocomplete works from usercontrol using webservice

I have jQuery to pull the autocomplete record as I type in the textbox, this data is being fetched using webservice. Now, everything works fine while using in Default.aspx page, but when I use this process from UserControl.ascx and call it in the default.aspx page then it doesn't return the autocomplete data (result).
WebService.asmx code:
[WebMethod]
public List<string> GetAutoCompleteData(string username)
{
string conString = ConfigurationManager.ConnectionStrings["MYCONNECTION"].ConnectionString;
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT SSName from SSRecord where SSName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["SSName "].ToString());
}
return result;
}
}
}
UserControl.ascx code:
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<link href="jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui.js" type="text/javascript"></script>
<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: "WebService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" class="autosuggest"></asp:TextBox>
Default.aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="~/UserControl.ascx" TagPrefix="uc1" TagName="UserControl" %>
<body>
<form id="form1" runat="server">
<div>
<uc1: UserControl runat="server" ID="UserControl"/>
</div>
</form>
</body>
I got the similar post on the below link. Therefore, after some modification mentioned in the link I am able to sort this out.
https://www.aspsnippets.com/Articles/Implement-jQuery-Autocomplete-using-Web-Service-in-ASP.Net.aspx

Failed to load resource: the server responded with a status of 500 (Internal Server Error) while sending post request via ajax

I am writing simple web service to save the data in cache and then retrieve it. When I press the save button, AJAX code runs on server and browser console shows me this error. My C# web service code is:
[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 stash : System.Web.Services.WebService
{
[WebMethod]
public bool save_value(string new_value)
{
//Session["newValue"] = new_value;
HttpRuntime.Cache["newValue"] = new_value;
if (HttpRuntime.Cache["newValue"] != null)
{
return true;
}
else
{
return false;
}
}
[WebMethod]
public string get_value()
{
object a = HttpRuntime.Cache["newValue"];
return a.ToString();
}
}
And html page code is ..
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
main page
</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#savebtn").click(function () {
var val = $("#txtsave").val();
$.ajax({
url: "stash.asmx/save_value",
method: 'POST',
contentType: 'application/json;charset-utf',
data: JSON.stringify({ new_value: val }),
dataType: 'bool',
//cache: true,
success: function (data) {
if (data == true) {
alert("value has been saved");
}
else {
alert("value did not saved");
}
},
});
});
$("#getbtn").click(function () {
$.ajax({
url: "stash.asmx/get_value",
method: 'GET',
datatype: 'json',
cache: true,
success: function (data) {
$("#txtget").val(data);
},
});
});
});
</script>
</head>
<body>
Type the value u want to save : <input type="text" id="txtsave" />
<input type="button" id="savebtn" value="save it" /><br /><br /><br />
get the value u just saved by pressing this button <input type="button" id="getbtn" value="get" />
<input type="text" id="txtget" />
</body>
</html>

Implementing Autocomplete textbox in ASP.NET

I am trying to get an autocomplete textbox working for my website on a web form. This is to autocomplete the textbox with house names once the user has started typing. The sql database is connected and the ado.net model is all set up. I just can't seem to figure out why it is not working.
The aspx page is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=txtHouseName%>").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebForm1.aspx/GetHouseName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Auto Complete Textbox without using Web Service</h3>
<table>
<tr>
<td>House Name: </td>
<td>
<div class="ui-widget" style="text-align:left">
<asp:TextBox ID="txtHouseName" runat="server" Width="350px" CssClass="textboxAuto" Font-Size="12px" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
and this is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Houses_of_Mayo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetHouseName(string pre)
{
List<string> allHouseName = new List<string>();
using (HOMEntities h = new HOMEntities())
{
allHouseName = (from a in h.Houses
where a.Name.StartsWith(pre)
select a.Name).ToList();
}
return allHouseName;
}
}
}

Ajax.abort() not working

I have read a lot of pages explaining how ajax.abort() should work but for some reason I cannot get this to work with my situation. Here is the code I have:
<script type="text/javascript">
$(document).ready(function () {
...
function abortxhRequest() {
xhRequest.abort();
}
var xhRequest
function SendFileToServer(blob, fileName) {
if (xhRequest) {
xhRequest.abort();
}
xhRequest = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
//Do something with upload progress
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
progressBar.css("width", percentLoaded + '%');
progressPercentage.text(percentLoaded + '%');
}
}, false);
//Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
//Do something with download progress
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
progressBar.css("width", percentLoaded + '%');
progressPercentage.text(percentLoaded + '%');
}
}, false);
return xhr;
},
type: "POST",
url: "myPage.aspx/SendFileToServer",
data: "{blob: \"" + blob + "\", fileName: \"" + fileName + "\"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// If there was no data show No Data display
if (msg.d == "success") {
$("#spManagePhoto").html("Complete!");
setTimeout(function () {
$("#divManagePhotoTakePhoto").show();
$("#divManagePhotoUploading").hide();
}, 2000);
}
},
error: function (xhr, status, thrownError) { //Something went wrong on front side
alert(xhr.responseText); //You don't want to read all that, lol
//alert(thrownError); //Right down to the point
}
});
}
});
...
</script>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
...
<div id="divManagePhotoUploading">
<center>
<div class="marginTop10"><span id="spManagePhoto" class="SubmittingText"></span></div>
<div class="marginTop20"><img src="Images/ajax-loader.gif" alt="Loading..." /></div>
</center>
<div id="divProgressBarShell" class="ui-corner-all">
<div style="margin:5px; position:relative">
<div id="progress_bar">
<table border="0" cellpadding="0" cellspacing="0" style="width:100%; height:100%"><tr align="center"><td valign="middle">
<div class="percent"></div>
<label class="PercentLabel">0%</label>
</td></tr></table>
</div>
</div>
</div>
<div>
<button onclick="abortxhRequest();" class="nav-button2" style="display:block">Cancel Upload</button>
</div>
</div>
...
</asp:Content>
When I click the Cancel Upload button, ajax throws an error. Status of the error is "error" and xhr.responseText is blank. What am I doing wrong? Any help with this is greatly appreciated.
Abort() triggers the error() in Ajax. This is JQuery's standard behavior.
Do this to detect error but not abort:
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus != "abort") { // aborting actually triggers error with textstatus = abort.
alert(errorThrown.message);
}
}
Here is a reference of this behavior:
http://paulrademacher.com/blog/jquery-gotcha-error-callback-triggered-on-xhr-abort/

Categories

Resources