I’m trying to create a application which posts data from view to my controller, this works. However when I try to use alerts for feedback(succes or error) it’s only giving me the error.
HTML:
API has been added!
API has not been added!
JQuery:
$(document).ready(function () {
$("#success-alert").hide();
$("#danger-alert").hide();
$("#btnSubmit").click(function () {
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/ApiBroker/AddApi",
dataType: 'json',
data: datastring,
success:
function () {
$("#success-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#success-alert").slideUp(500);
});
},
error:
function () {
$("#danger-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#danger-alert").slideUp(500);
});
}
});
$('#myModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
})
})
Controller:
[HttpPost]
public ActionResult AddApi(ApiRedirect model)
{
var data = model;
try
{
List list = dbProducts.ApiRedirects.ToList();
int companyID = dbProducts.Companies.Where(x => x.CompanyName == model.Company.CompanyName).FirstOrDefault().CompanyID;
int mappingID = dbProducts.MappingNames.Where(x => x.Name == model.MappingName.Name).FirstOrDefault().MappingID;
ApiRedirect api = new ApiRedirect();
api.ApiName = model.ApiName;
api.CompanyID = companyID;
api.ApiURL2 = model.ApiURL2;
api.MappingID = mappingID;
api.ResponseType = model.ResponseType;
dbProducts.ApiRedirects.Add(api);
dbProducts.SaveChanges();
return new HttpStatusCodeResult(200);
}
catch (Exception ex){
throw ex;
}
}
My controller inserts the data in my database and I’m returning a statuscode 200 in my controller. However the error instead of succes is getting handled in my JQuery.
Output when posting data:
UPDATE
When I use console.log(data) in my JQuery I’m getting the following output:
Does anyone have any suggestions?
Thanks in advance!
Ashley Alicia
You need to provide the right content type if you’re using JSON dataType. Before echo-ing the json, put the correct header.
Additional fix, you should check whether the query succeed or not.
On the client side: