AJAX TypeError: query is undefined - c#

I'm trying to do a ajax request to my controller in C#, but it never reaches the controller - I get a type Error saying "query is undefined".
Here is my ajax script:
$(document).ready(function () {
$.ajax({
url: '/Account/GetAllGamesWithRoles',
type: 'POST',
data: {},
success: function (games) {
debugger;
Games = games;
BuildGames(games);
},
error: function() {
}
});
});
Here is my controller action:
[HttpPost]
public ActionResult GetAllGamesWithRoles()
{
var result = MockGames();
return new JsonResult{ Data = result, MaxJsonLength = Int32.MaxValue};
}

try this
$(document).ready(function () {
alert('called before ajax');
$.ajax({
url: "/Account/GetAllGamesWithRoles",
type: "POST",
data: {'test':'testcall'},
success: function (data) {
Games = data.Data;
BuildGames(Games);
},
error: function (request, textStatus, errorThrown) {
alert("Status: " + textStatus + "Error: " + errorThrown);
}
});
});
[HttpPost]
public JsonResult GetAllGamesWithRoles(string test)
{
var result = MockGames();
return Json{ Data = result, JsonRequestBehavior.AllowGet};
}

Related

Not Receiving the query result to ajax function from asmx page asp.net

I'm working with the Ajax and jQuery in my app. When I return a query result it's not showing me that result. The Code is given below:
asmx page Code
[WebMethod, ScriptMethod]
public void Getusertimelist(string id)
{
List<UserhoursList> employeelist = new List<UserhoursList>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString))
{
con.Open();
SqlCommand command12 = new SqlCommand(" SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, Total_time) * 3600 ) + ( DATEPART(mi, Total_time) * 60 ) + DATEPART(ss, Total_time)), 0)) From Todaywork Where Id='"+id+"'", con);
string getvalue = command12.ExecuteScalar().ToString();
UserhoursList employee = new UserhoursList();
employee.Total_Time = getvalue;
employeelist.Add(employee);
con.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employeelist));
//return id;
}
Ajax Code
<script type="text/javascript">
$(document).on("click", ".get_time", function () {
var timeid = $(this).data('id');
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: { id: timeid },
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
});
$(document).ready(function () {
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
});
});
</script>
It's not showing me the answer because when I remove that (string id) parameter then it works perfectly. When I use it's not showing me the answer. I want to complete my project but this error not pushing me. Any help plz.
Your first request looks good. But in your second request, I don't see that you're using the jQuery DataTable data option.
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
// Where is data: { id: timeid }?
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
I think it will work if you change data to send a string
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: '{ "id": ' + timeid + '}',
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
an alternative is do something like
var dat = {}
dat.id = timeid
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: JSON.stringify(dat),
success: function (data) {
//alert(data);
},
error: function (err) {
}
});

jQuery AJAX Not Calling A C# Function In ASP.NET MVC

Basically, I am trying to call controller from views using jQuery ajax but it's not calling controller.
What I have to do is passing my token value from registration page to controller so that I will use its value for user registration.
< script type = "text/javascript" >
document.getElementById('LoginWithAmazon').onclick = function() {
options = {
scope: 'profile'
};
amazon.Login.authorize(options,
function(response) {
if (response.error) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token) {
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: {
token: 'abc'
},
cache: false,
success: function(result) {
alert(result);
}
});
}
function receiveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].Data);
}
}
}
return false;
};
< /script>/
Here below is my controller code
public JsonResult ProfileInfo(string token) {
return Json("test", JsonRequestBehavior.AllowGet);
}
I need to pass the token value from registration page to my controller
Try to change this in the controller
return Json("test", JsonRequestBehavior.AllowGet);
into
enter code herereturn Json(new { value="test" }, JsonRequestBehavior.AllowGet);
and change your js to be like this
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: JSON.stringify({
token: 'abc'
}),
cache: false,
success: function(result) {
alert(result);
}
});
Finally, i have solved the problem.I am unable to call the account controller so i have used my home controller for this purpose.Here below is the code that i have used for calling controller :
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
options = { scope : 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token)
{
var url = "/home/ProfileInfo?token=" + token;
var request = $.ajax({
url: url,
method: "GET",
dataType: "json"
});
request.done(function (msg) {
var data = [];
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
});
}
}
</script>

Fail to send array of string using ajax C#

I have some trouble to send an array of string using ajax to a C# controller.
I tried many things but i can't make it works.
Here is my C# controller :
[HttpPost]
[Route("getavailabilities")]
[Authorize]
public IActionResult GetAvailabilities(string[] data)
{
return StatusCode((int)HttpStatusCode.OK, new
{
data = ""
});
}
Then my ajax call :
function apiExecuteRequest(callback, uri, type, data) {
$.ajax({
url: uri,
type: type,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: (apiReply) => {
callback(apiReply);
},
failure: (xmlHttpRequest, textStatus, errorThrown) => {
callback({ isSuccess: false, error: textStatus + " " + errorThrown, message: xmlHttpRequest.responseJSON });
},
error: (xmlHttpRequest, textStatus, errorThrown) => {
callback({ isSuccess: false, error: textStatus + " " + errorThrown, message: xmlHttpRequest.responseJSON });
}
});
}
function apiExecuteAuthenticatedRequestAsync(callback, uri, type, data) {
apiGetTokenAsync((token) => {
$.ajaxSetup({
beforeSend: (xhr) => {
xhr.setRequestHeader("Authorization", "bearer " + token);
}
});
apiExecuteRequest(callback, uri, type, data);
});
To get my array i use :
var data = this.values2.map(function (item) {return item.ItemId;})
apiExecuteAuthenticatedRequestAsync((response) => {
...
}, apiUrl + 'dashboard/getavailabilities', "POST", data);
What i get is everytime Null.
When i set the parameter to object or dynamic i get : {object}.
I really need your help, and thank you for any advice and help you would provide me.
As you know that the dataType of the request is application/json. So you need to convert the data to Json String using JSON.stringify like so:
var data = this.values2.map(function (item) {return item.ItemId;})
apiExecuteAuthenticatedRequestAsync((response) => {
...
}, apiUrl + 'dashboard/getavailabilities', "POST", JSON.stringify(data));

jQuery ajax call not hitting controller due large string data parameter

In my view file, I'm making an ajax call as follows:
$.ajax(
{
url: '#Url.Action("LMTDetailDashboardList", "DetailUsage")',
dataType: "json",
data:
{
ServerID: ServerID,
LicenseId: LicenseId,
company: company,
fromDate: fromDate,
toDate: toDate,
fromhour: fromHour,
toHour: toHour
},
type: "GET",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
beforeSend: function () {
$("#divLoading").show();
},
success: function (data) {
LMTDetailDashboardChart(data, Zaxis);
return false;
},
#*error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},*#
//error: function (jqxhr, status, exception) {
// alert('Exception:', exception);
//},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
console.log('Could not get posts, server response: ' + textStatus + ': ' + errorThrown);
},
complete: function () {
$("#divLoading").hide();
$("#exportuserlist").show();
}
});
return false;
The controller code is as follows:
public JsonResult LMTDetailDashboardList(String ServerID, String LicenseId, String Company, String FromDate, String ToDate, String FromHour, String ToHour)
{
int nameLength = Company.Length;
int nameLength2 = ServerID.Length;
int nameLength3 = LicenseId.Length;
System.Text.ASCIIEncoding.ASCII.GetByteCount(Company);
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
TempData["Company"] = Company;
TempData["ServerID"] = ServerID;
TempData["LicenseId"] = LicenseId;
TempData["FromDate"] = FromDate;
TempData["ToDate"] = ToDate;
TempData["FromHour"] = FromHour;
TempData["ToHour"] = ToHour;
if (object.Equals(ServerID, null))
{
ServerID = "All";
}
try
{
var response = objLMTDAL.GetLMTDetailUsage(ServerID, LicenseId, Company, FromDate, ToDate, FromHour, ToHour);
if (!object.Equals(response, null))
{
objLMT.LMTDetailUsageList = response.ToList();
}
}
catch (Exception ex)
{
throw;
}
return Json(objLMT.LMTDetailUsageList, JsonRequestBehavior.AllowGet);
}
When the "company" value is smaller in length/size ajax call hits the controller action but when it is larger, it throws an error and it doesn't hit the controller method.
I have tried to rectify errors in many ways but not able to get it. With browser debugger, I am now getting following error. Error Screen
Note: "company" variable contains the comma separated values from the multi-select drop-down.
Kindly put some light on it.
The problem is because of the data length. The GET requests have length restrictions. That's why the ajax call not hitting the controller. You can use a POST instead of GET method. The POST requests have no restrictions on data length.
Change the 'type' using the following way:
type: "POST",
Your final script will be:
$.ajax(
{
url: '#Url.Action("LMTDetailDashboardList", "DetailUsage")',
dataType: "json",
data:
{
ServerID: ServerID,
LicenseId: LicenseId,
company: company,
fromDate: fromDate,
toDate: toDate,
fromhour: fromHour,
toHour: toHour
},
type: "POST",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
beforeSend: function () {
$("#divLoading").show();
},
success: function (data) {
LMTDetailDashboardChart(data, Zaxis);
return false;
},
#*error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},*#
//error: function (jqxhr, status, exception) {
// alert('Exception:', exception);
//},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
console.log('Could not get posts, server response: ' + textStatus + ': ' + errorThrown);
},
complete: function () {
$("#divLoading").hide();
$("#exportuserlist").show();
}
});
return false;
Good Luck!

Ajax value not received by controller

I have this code that got properly delivered to its controller counterpart.
but for some reason the search model data was only nulls,while the pageNumber is received properly
did i made a mistake somewhere?
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var searchModel = {
xval: xData,
yval: yData,
};
var pageNumber = #Model.Page +1;
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: { 'searchModel': searchModel, 'pageNumber': pageNumber },
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
the Controller is as such
[HttpGet]
public ActionResult FilterData(WorkSearchModel searchModel,int? pageNumber)
{
EDIT:
as suggested i tried doing doing both on a different project (this makes the function uncallable so i presume there's an error somewhere)
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var searchModel = {
xval: xData,
yval: yData,
pageNumber = #Model.Page +1
};
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: searchModel,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
i also have tried to do this but nothing works (this gives null values for both searchmodel and pagenumber now)
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: JSON.stringify(searchModel, pageNumber),
contentType: "application/json;",
I would change the call from a GET to POST
One solution is to send the parameters one by one in the query string like this
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var pageNumber = #Model.Page +1;
$.ajax({
url: "/Work/FilterData?xval=xData&yval=yData&pageNumber=pageNumber",
type: "GET",
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
And the controller
[HttpGet]
public ActionResult FilterData(int xval, int yval, int? pageNumber)

Categories