I have the following method inside my page model which is called Order
public async Task<IActionResult> OnPostAddRecord(string recordId)
{
return new JsonResult("Hello");
}
My Ajax code to call said method:
$('#RecordList').change(function () {
var formData = {
recordId: $("#RecordList").val(),
};
$.ajax({
type: 'POST',
data: formData,
url: '#Url.Page("order", "addrecord")',
success: function (result) {
alert(result)
},
error: function (result) { }
});
});
Yet when it's fired it returns StatusCode 400, however, I have another Ajax method on the same page that works successfully, the difference is that one is a GET whereas this is a POST.
I really can't see what the problem is here.
You need to include the request verification token in your FormData: https://www.mikesdotnetting.com/article/336/ajax-posts-in-razor-pages-and-http-400-errors
Related
I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});
In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
I need to use the info from the list returned in a method that calls my ajax to c#.
This is the method, seems working fine:
public JsonResult getComandes(int id)
{
using (var db = new daw_tenda()) //estat 1 = acabat, estat 2 = en curs.
{
var llistacomandes = db.Comandes.Where(x => x.usuaris_id == id).ToList();
return Json(llistacomandes.ToList(), JsonRequestBehavior.AllowGet);
}
}
This is my ajax:
$.ajax({
url: "/Perfil/getComandes",
type: 'get',
dataType: 'json',
data: {
id: $("#idsesion").val()
},
success: function (response) {
$("#contingutcomandes").show();
$("#contingutperfil").hide();
if (response)
{
console.log(response);
}
}
});
I'm not getting any response, neither it's working first two jquery show and hide and i don't know what am i doing wrong, my method is working fine and is returning the list but i can't get it from the ajax call, what i have to fix?
Hmm -- since the method is correctly returning the list, the symptoms suggest the success function isn't being called. Have you tried changing success to complete? This'll execute even if the request is failing, which may shed some light.
Maybe something like:
complete: function(resp){
console.log("Ding!");
console.log(resp);
}
call back in not being called.
function GetTrainingResults(id,callback){
$.getJSON("/dashboard/GetTrainingResults/", {'id':id}, callback);
}
GetTrainingResults('id',function(result){
alert(result);
});
and code behind is
public ActionResult GetTrainingResults(int id)
{
string test = "You are there.";
return Json(test, JsonRequestBehavior.AllowGet);
}
Or suggest and another way. Task in to call controller method and wait for method response in javascript.
Thanks
If you use jQuery.ajax, you'll at least be able to see the error being returned by the server:
function getTrainingResults(id, callback) {
$.ajax({
url: "/dashboard/GetTrainingResults/",
data: {id: id},
success: function(data) {
callback(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
callback(errorThrown);
}
});
}
id in your Action method takes an int, yet you're passing it a string of 'id' in your JS. Either change your JS or you action method so that the types match.
Check that your request is returning successfully, the ajax shorthand functions only call the callback if the request is successful (ie status code 200 and of the right data type, ie json). Try the full .ajax jquery function and see whats going on under the hood.
.getJSON() is equivient too
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so it might be hitting error: due to the data type.
Source http://api.jquery.com/jQuery.getJSON/
My code makes an ajax call:
$.ajax({
url: "/Controller/EmailUserKeys",
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
It calls an action in my controller which returns some JSON:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true });
}
My problem is that the ajax error function is called and not the ajax success function.
Why?
PS. If my action returns "return null;", the ajax success function is called.
You must allow GET which is disabled by default when returning JSON results:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
or use a POST request:
$.ajax({
url: "/Controller/EmailUserKeys",
type: "POST",
dataType: 'json',
data: { userId: 'some user id' },
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
Also never hardcode the url to your controller action as you did. Always use url helpers when dealing with urls in an ASP.NET MVC application:
url: "#Url.Action("EmailUserKeys", "Controller")",
And here's a piece of advice: use a javascript debugging tool such as FireBug if you are doing any web development. Among with other useful things it allows you to inspect AJAX requests. If you had used it you would have seen the response sent from the server which would have looked like this:
This request has been blocked because sensitive information could be
disclosed to third party web sites when this is used in a GET request.
To allow GET requests, set JsonRequestBehavior to AllowGet.
And you wouldn't need to come to StackOverflow and ask this question as you would have already known the answer.
You should edit your code to this:
public JsonResult EmailUserKeys(string UserId)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
See the official documentation for more info:
http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior.aspx
The reason for disabling this by default is because of JSON hijacking. More information about this can be found here:
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
Hope this helps you out!