cannot get request from JQuery - javascript

I have auto complete input field, so I have done a function to retrieve data based on user request. I have tested the function with webform and it works fine, but when I tried to use api and send request to controller, the controller does not receive any request from JQuery?
JQuery:
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/Employee/GetRe",
data: "{'term':'" + $("#auto").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
controller:
[HttpGet]
public string GetRe(string term) {
var re = repository.GetCategory(term);
return re.First();
}
function:
[WebMethod]
public string[] GetCategory(string term)
{
List<string> retCategory = new List<string>();
connection();
string query = string.Format("select FirstName from Employee where FirstName Like '%{0}%'", term);
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
retCategory.Add(reader.GetString(0));
}
}
con.Close();
return retCategory.ToArray();
}
}
and it shows this error
"No action was found on the controller 'Employee' that matches the
request ."}

You are formatting your JSON object as a string.
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/Employee/GetRe",
data: {'term': $("#auto").val()},
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});

Related

Ajax success event doesn't fire

Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}

How to get data from Ajax

I have a variable called sid which handle number of seat. I want to throw sid to TryJSON.aspx method test. then I wanna do manipulate data on method test then throw back the result to this ajax. but I have an error when I just try to throw sid
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);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
this is my C# code to receive noSeat
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
// return noSeat;
//JavaScriptSerializer serializer = new JavaScriptSerializer();
// return new JavaScriptSerializer().Serialize(new { noSeat = noSeat });
}
I have try return only noSeat and also with Javascript serializer. but it has an error. it says
An attempt was made to call the method 'test' using a POST request, which is not allowed.
I have been tried
return "Success !!"
but it doesn't appear on console and still same error.
what's the matter ?
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",
dataType:'json',
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");
}
});

Autocomplete returns an error on ajax request

I am trying to use jQuery Autocomplete on a text box, but it's not working.
Here is my script to get autocomplete list from database but it gives me error and alerts error message.
$(function () {
$("#ContentPlaceHolderSearch_txt_Search").autocomplete({
source: function (request, response) {
$.ajax({
url: "Service/AutoComplete.asmx/GetCompletionListName",
data: "{ 'prefixText': '" + 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
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
Here Is my server code
[WebMethod]
public string[] GetCompletionListName(string prefixText, int count)
{
List<string> items = new List<string>(count);
GA_UsersTableAdapter uta = new GA_UsersTableAdapter();
UserControllar.GA_UsersDataTable udt = uta.GetDataByNameAutoComplete(prefixText);
foreach (DataRow row in udt.Rows)
{
items.Add(row["Full_Name"].ToString());
}
return items.ToArray();
}
i just changed my service path in script from
url: "Service/AutoComplete.asmx/GetCompletionListName"
to
url: "../Service/AutoComplete.asmx/GetCompletionListName"
and it works now...

Receive a complex object from jquery in mvc controller

I am trying to submit a object from a form to my mvc controller.
here is the js:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.user = jQuery('#selectUser').val();
model.roleslist = usersRoles;
console.log('model: ' + 'user: ' + model.user + 'roles: ' + model.roleslist);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("
AddUser ")",
dataType: "json",
//data: { model: JSON.stringify(usersRoles) },
data: {
model: JSON.stringify(model)
},
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
now that fetches al the necessary info and builds the object "model" and then posts it to the controller.
Here is my view model:
//for receiving from form
public class submitUserRolesViewModel
{
public string userId { get; set; }
public List<String> rolesList { get; set; }
}
Here is my controller:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(StrsubmitUserRolesViewModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
How can I receive a json object in the controller? Now currently my model is null when a post is executed by the jquery. This means that it is not binding correctly. I am sure there is just something small wrong here.
Could you please point out where I am going wrong.
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { alert(data); },
error: function (errMsg) {
alert(errMsg);
}
});
I slightly modified you JQuery and it is working as expected now -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
var rolesArray = jQuery.makeArray(roles);
var model = new Object();
model.userId = 1;
model.rolesList = rolesArray;
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(model),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
Output -

Server side method not getting called

From the below javascript code i am trying to call a serverside method, but serververside method is not getting called. I am using jquery, ajax
<script type="text/javascript" src="JquryLib.js"></script>
<script type="text/javascript" language="javascript">
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var v1 = 'StateId: ' + StateId;
$.ajax(
{
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: '{' + v1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
</script>
This is my serverside method which i need to call.
private static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
It is giving me the following error: 500 (Internal Server Error)
I cannot figure out what is wrong. please help!
Stack Trace:
[ArgumentException: Unknown web method PopulateCities.Parameter name: methodName]
use this script:
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var data = {
'StateId': StateId
};
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: JSON.stringify(data), // using from JSON.stringify is much better than to try stringify data manually
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and this code for your code behind:
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
Use this script
function GetCities(StateId) {
debugger;
var v1 = "{'StateId': '" + StateId+"'}";
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: v1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and modify Code Behind
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}

Categories

Resources