$.getJSON is not calling call back function - c#

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/

Related

Ajax call to MVC controllers

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....
I've implemented the following code within my MVC controller
[HttpPost]
public string tt(string o)
{
return o;
}
[HttpPost]
public string tt2(string o)
{
return "lala";
}
And I'm triggering the following ajax calls from the browser
$.ajax({
url: "/Home/tt2",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
$.ajax({
url: "/Home/tt",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
As a result when running the first ajax call the result is
lala correct
And for the second ajax call, the result is
undefined correct
In the mean time these are some stuff I tried
Adding dataType: "json", to the ajax call
Changing the string data from {o: 'asdas'} to 'asdas'
Removing the JSON.stringify
Adding the charset=utf-8 to the contentType
Changing the ajax call type and MVC controller method from POST to GET to PUT
Changing the MVC controller method parameter from string to int
Removing the error method from the ajax call
Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})
I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..
Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..
Any thoughts on how to make ajax call work?
try:
[HttpPost]
public string tt([FromBody]string o)
{
return o;
}
Your request should be like this:
$.ajax({
url: '#Url.Action("tt", "Home")',
data: {
"o": "asdasdas"
},
cache: false,
type: "POST",
success: function (response) {
},
error: function (xhr) {
}
});

MVC Controller Return Content vs Return Json Ajax

In MVC, why does returning Content sometimes fail in the Ajax callback, while returning Json works, even for simple string objects?
Even when it fails, the data is still available if you were to access it in the always callback...
Update:
When I set the contentType in the ajax call to text/xml the response will no longer enter the error message.
AJAX:
$.ajax({
cache: false,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
url: "/MyController/GetFooString",
data: { },
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Ajax Failed!!!");
}
}); // end ajax call
Controller Action That Fails (Sometimes)
Even when it fails, the data is still available.
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Content(Foo);
} // end GetFooString
Controller Action That Always Works
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Json(Foo, JsonRequestBehavior.AllowGet);
} // end GetFooString
Using Content(Foo); sends a response that doesn't have the mime type header. This happens because you're not setting ContentType when using this overload. When the Content-Type is not set, jQuery will try to guess the content type. When that happens, whether it can successfully guess or not depends on the actual content and underlying browser. See here:
dataType (default: Intelligent Guess (xml, json, script, or html))
Json(...) on the other hand explicitly sets the content type to "application/json" so jQuery knows exactly what to treat the content as.
You can get consistent result from Content if you use the 2nd overload and specify a ContentType:
return Content(Foo, "application/json"); // or "application/xml" if you're sending XML
But if you're always dealing with JSON, then prefer using JsonResult
return Json(Foo, JsonRequestBehavior.AllowGet);

jQuery ajax call doesn't seem to do anything at all

I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.

Ajax call returns internal 500 error

Hi I am trying to execute an ajax call to the server but I seem to have no luck I keep getting back on the console an error 500 Internal server error.This is my ajax call:
$("body").on("click", "#ok", function (e) {
var id = $(this).attr("data-bookid");
$.ajax({
url: "/ProductEditor/DeleteBook",
type:"POST",
data: { bookId: parseInt(id) },
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
e.preventDefault();
})
And this is the C# code I am trying to call:
public ActionResult DeleteBook(int bookId)
{
bookRepository.DeleteBook(bookId);
return RedirectToAction("Books", "ProductManager");
}
While trying to debug I have noticed that the DeleteBook method is not even called.
What am I doing wrong?
EDIT I have added the [HttpPost] attribute but it still does not work
Without more information, it's not easy to tell you what you are doing wrong.
However, the error function callback for the jQuery ajax function takes three parameters:
(jqXHR, textStatus, errorThrown)
$.ajax({
url: "/ProductEditor/DeleteBook",
type:"POST",
data: { bookId: parseInt(id) },
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
The third parameter, errorThrown will have the HTTP response text for the call to /ProductEditor/DeleteBook. I would suggest looking at what errorThrown is showing, as well as possibly running the entire program in debug mode.
Perhaps var id = $(this).attr("data-bookid"); is incorrect, and the value of id is being set to undefined?
Also, you can use the Network tab in the F12 Development Tools in IE or Chrome, Firebug in Firefox, or Fiddler to debug ajax calls. You can watch the ajax request being sent to the server as well as the response from the server in order to see whether the correct data (bookId) is being sent in the correct format (JSON) and what the response is from the server
Your WebMethod must be static
[WebMethod(true)]
public static ActionResult DeleteBook(int bookId)
{
bookRepository.DeleteBook(bookId);
return RedirectToAction("Books", "ProductManager");
}
Add HttpPost to your method and try
[HttpPost]
public ActionResult DeleteBook(int bookId)
{
bookRepository.DeleteBook(bookId);
return RedirectToAction("Books", "ProductManager");
}

jQuery $.ajax success not firing from JsonResult

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!

Categories