How to call web api in html page using jquery? - c#

I am learning web api where I have created a html page and I want to get <ul> list in my html page.
To call api i have used Jquery ajax call to do so but seems not working. I debugged Jquery but getting no error.
Please suggest me where i am going wrong.
My html code
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
var listitem = $('#ulEmployees');
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
dataType: JSON,
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});
$('#btnClear').click(function () {
listitem.empty();
});
});
</script>
</head>
<body>
<input id="btn" value="Get All Employees" type="button" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
Web api GET method
public class EmployeesController : ApiController
{
public HttpResponseMessage Get(string gender="All")
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
switch(gender.ToLower())
{
case "all":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.ToList());
case "male":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList());
case "female":
return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList());
default:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Not found");
}
}
}
}

The datatype should not be passed. Your function should be like below with out datatype as JSON. Internally in jquery the call will fail while it is trying to convert datatype with .toLower function.
$('#btn').click(function () {
debugger;
$.ajax({
Type: 'GET',
url: 'api/employees',
success: function (data) {
listitem.empty();
debugger;
$.each(data, function (index, val) {
var fullname = val.FirstName + ' ' + val.LastName;
listitem.append('<li>' + fullname + '</li>');
});
}
});
});

Related

Ajax Call not hitting controller when page is loaded

I have an ajax call that seems to be working fine on another page, however when i call it on this page it doesnt work.
CSHTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Script/jquery-1.12.2.min.js"></script>
<script src="~/Script/moment.js"></script>
<script type="text/javascript">
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
function initialiseForms() {
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).success(function (response) {
alert(JSON.stringify(response));
});
}
</script>
</head>
<body onload="initialiseForms()">
<h1 id="titleText"></h1>
<form id="evolveFormsForm" method="post" target="_self" action="Test">
<input type="hidden" id="formPackEventData" name="formPackEventData" value="" />
<input type="hidden" id="selectedTemplateCodes" name="selectedTemplateCodes" value="" />
<input type="hidden" name="logonMethod" value="automatic" />
</form>
</body>
</html>
Controller
public ActionResult Index()
{
return Json(new { success = true, rtn = "TEST" }, JsonRequestBehavior.AllowGet);
}
This alert(JSON.stringify(response)); works in the response but the breakpoint is not hit and the alert just displays an empty string.
Cheers
Shouldn't your ajax be like this?
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response)
{
alert(JSON.stringify(response));
},
success(function (response)
{
alert(JSON.stringify(response));
}
})
instead of
$.ajax({
type: 'POST',
url:'#Url.Action("Index", "Home")',
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).success(function (response) {
alert(JSON.stringify(response));
});
I feel like you have the success outside of the actual ajax as well as having an extra )
EDIT: An easy way for us to help you would be if you add a debugger; into the function itself and tell us if it throws an error in Google DevTools

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>

AutoComplete for Asp.net C# Not working?

I have tried everything. I am trying to get autocomplete to work for an input textbox and I can't get it to work. I am implementing it into a DNN webpage here is the code I am using for this autocomplete...
I keep getting error every time.
I am welcome to do a teamviewer session.
Thank you.
ASP.NET code
<asp:Panel ID="pnlInfoSearch" runat="server">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></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: "View.ascx/GetPartNumber",
data: "{'PartNumber':'" + document.getElementById('txtPartNum').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<div id="introcopy">
<h2>Product Info Center</h2>
<p>Download technical and quality documents, check inventory and order samples for your parts.</p>
</div>
<div class="demo">
<p>Enter a part number (or portion of a part number) to retrieve information about that product.</p>
<input type="text" id="txtPartNum" value="Enter part #..." style="height: 18px" class="autosuggest" />
</div>
<script type="text/javascript">
// <![CDATA[
var _sDefaultText = 'Enter part #...';
jQuery('#txtPartNum').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
window.location.href = '<%= new Uri(String.Concat("http://", Page.Request.UserHostName, Page.Request.RawUrl)).AbsolutePath %>?partnum=' + jQuery(this).val();
}
}).focus(function () {
if (jQuery(this).val() === _sDefaultText) {
jQuery(this).val('');
}
}).blur(function () {
if (jQuery(this).val().length == 0) {
jQuery(this).val(_sDefaultText);
}
});
// ]]>
</script>
<br class="clear" />
</asp:Panel>
C# code....
[WebMethod]
public static List<string> GetPartNumber(string PartNumber)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("HIDDEN"))
{
using (SqlCommand cmd = new SqlCommand("select PartNumber from Products.Products where PartNumber LIKE #SearchText+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#SearchText", PartNumber);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["PartNumber"].ToString());
}
return result;
}
}
}
If you think your issue is SQL related, then refactor the SQL related code and write some tests against that method with some know part numbers.
Looking at your code, the URL for your service method stands out. You specify You specified url: "View.ascx/GetPartNumber" but I would assume you either meant something else (maybe View.ashx or View.asmx). Are you able to hit your service method via your browser as a simple GET?
What do you get when you access this URI in your browser? /View.ascx/GetPartNumber?PartNumber=xyz

run method after jquery confimation

How would I run a method in backend to send emails when I have a jquery dialogue with yes and no button as following :
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true
});
});
$(".confirmLink").click(function (e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
$("#dialog").dialog({
buttons: {
"Yes": function () {
$(this).dialog("close"),
SendEmail(),
window.location.href = targetUrl;
},
"No": function () {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
</script>
<a class="confirmLink" href="emailsend.aspx"></a>
<div id="dialog" title="Confirmation Required">
<p>
Do you want to send an email?</p>
</div>
You would have to communicate this with the back end via ajax, the backend would then send the email; a little like this:
function SendEmail(email, content)
{
var data = "email=" + escape(email) + "&content=" + escape(content);
$.ajax({
url: "sendemail.asp",
type: 'POST',
data: data,
success: function(data){
alert("Hurray");
},
error: function() {
alert("Oh noes! It went wrong");
}
});
}

How to get jQuery auto-complete "tagify" values in C# ASP.Net

I'm using Tagify, which is basically using jQuery Autocomplete,
references :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<script src="../../../Scripts/jquery.tagify.js" type="text/javascript"></script>
<link href="../../../Styles/jqueryTagify.css" rel="stylesheet" type="text/css" />
Script :
<script>
var myTextArea = $("#txtbox").tagify();
myTextArea.tagify('inputField').autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "Demo.aspx/GetKeyword",
data: "{'match': '" + request.term + "'}",
dataType: "json",
contentType: "application/json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item,
}
}));
}
});
},
position: { of: myTextArea.tagify('containerDiv') },
close: function(event, ui) { myTextArea.tagify('add'); },
});
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
return false;
});
</script>
HTML is :
<input type="text" id="txtbox" />
<input class="submit" type="submit" value="Get Values" />
So when we clicked on submit button, we get tags value from here
var tagStr = $("#txtbox").tagify('serialize');
and when I clicked on getvalues the result like this
How could I get those values in the Code Behind in C#?
add a hidden field in html:
<input id="hiddenTags" name="tags" type="hidden"/>
and update submit js:
$('form').submit( function() {
var tagStr = $("#txtbox").tagify('serialize');
alert( "Got tags: " + tagStr );
$('#hiddenTags').val(tagStr);
return false;
});
now you can get tags in c#:
string tags = Request.Form["tags"];

Categories

Resources