ajax call results in error instead of succes - asp.net-mvc-3

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?

I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow

Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });

Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Related

Unable to 'call' controller action from ajax post

I'm using net.core for the first time today and I'm trying to call an action method from an ajax call:
My Ajax call (from a normal HTML page)
$("#contactMap").click(function (e) {
e.preventDefault();
var url = "/MapObjects/mapContact";
//I've tried MapObjectsController & '#Url.Action("mapContact", 'MapObjects")'; But to no avail
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
And in my controller:
namespace myName.Controllers
{
public class MapObjectsController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult mapContact()
{
Account account = new Account();
return Json(account);
}
}
}
The 'account' is just a normal model (obvs empty in this case). All I receive is a 404 error in the console though.
As mentioned this is the 1st time I've .net Core (this is code I've written loads of times in 'normal' MVC projects) so it's possible that I'm missing something really obvious.
Thanks,
C
The first, try to call the #Url.Action() explicitly in the Ajax call :
$("#contactMap").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("mapContact", "MapObjects")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (result) {
alert("success");
}
});
});
The second, check your routing rules.

Return bool value from Ajax

I am calling the below function from my .aspx page and all I want to check whether this function returned true or false. I tried many things but I get undefined as result.
I am calling function using below code
if (IsIncetiveAllowed())
{
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
function IsIncetiveAllowed() {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
return true;
else
return false;
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
Please Help!
If you pass a callback to the IsIncetiveAllowed function, you can make it execute your code with the result of the ajax call after it has been made.
IsIncetiveAllowed(function(is_allowed) {
if (is_allowed) {
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
else {
// Not allowed
}
});
function IsIncetiveAllowed(callback) {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
callback(true);
else
callback(false);
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
First off, you never want to use synchronous Ajax. Synchronous Ajax blocks the browser, the user interface freezes and the user cannot scroll, click or do or anything while synchronous requests load. Don't use them.
Second, it's useful to break up your operation into separate parts. What you have here is
A part can post JSON to the server
This is the most re-usable part, it works the same for all JSON you want to post to any URL.
A part that knows how to talk to to a specific endpoint on the server
This is the second most reusable part, it can send any data to a specific endpoint.
A part that uses this endpoint
This is the least reusable part, it can send specific data to a specific endpoint.
It makes sense to have a separate function for each part. jQuery supports this easily, because all Ajax methods return promises, and promises can be given from function to function.
Part 1, as a jQuery extension for maximum re-usability:
$.fn.postJSON = function(url, data) {
return $.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data)
});
};
Part 2, as a stand-alone function. Note that I am matching the remote API endpoint name. You can write more functions like this to wrap other API endpoints.
function checkIncentiveAllowed(typeOfApp) {
return $.postJSON("pp060.aspx/CheckIncentiveAllowed", {
typeOfApplication: typeOfApp
}).fail(function (err) {
MessageBox.Show("An error occurred in checkIncentiveAllowed method.",
null, MessageBoxButtons.OK, MessageBoxIcon.Error);
console.log(err);
});
}
Part 3, to be used inside an event handler for example:
checkIncentiveAllowed(m_TypeOfMortgage).done(function (response) {
var path = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']",
xmlNode = $(XMLCombos).xpath(path)[0];
if (response.d && xmlNode) {
xmlNode.parentNode.removeChild(xmlNode);
} else {
// not allowed
}
});
Well this is happening because the ajax call is asynchronous. You can put your code present in if block to the ajax callback function to implement your logic

MVC Ajax Post error

I am getting error while I post Ajax request to controller method. In controller method I need to pass Model class object.
But it gives me 500 Internal server error.
Can anybody help me to make it correct?
Mu code is as per below:
jQuery:
var request = $("#frmHost").serialize();
$.ajax({
url: "/Host/HostItemDetails/" ,
type: "POST",
datatype: 'json',
contentType : "application/json",
data: request,
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
Controller Method :
[HttpPost]
public JsonResult HostItemDetails(ClsHost objHost)
{
//Code here
return Json("1111");
}
Nirav Try this,
Parse the serialized data as a JSON object and later stringify that while posting using JSON.stringify().
$("#Button").click(function () {
var data = $("#frmHost").serialize().split("&");
var request = {};
for (var key in data) {
request[data[key].split("=")[0]] = data[key].split("=")[1];
}
$.ajax({
url: "/Home/HostItemDetails/",
type: "POST",
datatype: 'json',
contentType: "application/json",
data: JSON.stringify(request),
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
});
I ran the same code that you are running.
To test the code I did the following changes. I took a button, and on click event I am sending the post back to the controller.
the '[HttpPost]' attribute is fine too.
Can you make one thing sure, that the frmHost data matches to the class ClsHost,but still that shouldn't cause the server error, the error will be different.
$(document).ready(function () {
$("#clickMe").click(function () {
var request = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';
$.ajax({
url: "/Home/HostItemDetails/",
type: "POST",
datatype: 'json',
contentType: "application/json",
data: request,
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
});
});
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult HostItemDetails(ClsHost objHost)
{
//Code here
return Json("111", JsonRequestBehavior.AllowGet);
}
It is solved by removing same property name in Model class. It is mistakenly added by me twice.

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

Resources