$.ajax data is null - ajax

I need to save the record in the database. I have been doing this thing but I don't know for what reason it is giving me this error. Any help will be appreciated. I don't know why the data is null. Please refer to the error show in below screenshot:
data is not defined
function submit(amount) {
var _url = ' /Home/SaveDepositedAmount';
console.log(_url);
$.ajax({
type: "POST",
async: false,
cache: false,
beforeSend: function () { ShowLoading(); },
url: _url,
processData: false,
contentType: false,
dataType: 'json',
data: { amount: amount },
})
.done(function (data) {
Server side code is:
[HttpPost]
public JsonResult SaveDepositedAmount(int amount)
{
JsonResult result = new JsonResult();
int userId = Authentication.Instance.User.UserId;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}

You’re passing an object through to the server side but it’s only expecting an int.
Create an object with 1 property (int Amount) and use that instead of the int for your server side parameter

Related

Post ajax data to MVC controller

I have the following ajax in a .chtml file:
var planID = $("#PlanID").val();
if (planID.length == 4) {
$(ctl).prop("disabled", true).text(msg);
$("#nextButton").prop("disabled", true);
setTimeout(function () {
$(".submit-progress").removeClass("hidden");
}, 1);
$.ajax({
type: "POST",
url: "/ForgotUserID/CheckPlanID",
data: '{planID: "' + planID + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("ajax success function");
$("form").submit();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
//$("form").submit()
}
And I have the following in my ForgotUserIDController:
[HttpPost]
public JsonResult CheckPlanID(string planID)
{
ForgotUserID forgotUserID = new ForgotUserID()
{
PlanID = planID
};
return Json(forgotUserID);
}
When I run the code, I see this in the dev tools under network:
So I know the data that I typed into my input box is floating around somewhere.
When I have a breakpoint set in my controller, the value of planID is null. Shouldn't the value get passed from the ajax data component?
How can I get the data typed into the input box passed to my controller?
Any assistance is greatly appreciated.
Thank you!
if you want to use contentType: "application/json; charset=utf-8",
fix ajax data line
data: JSON.stringify({ planID : planID }),
and create viewmodel and use frombody attribute in action
public JsonResult CheckPlanID([FromBody] PlanViewModel model)
{
string planID=model.PlanID;
....
}
public class PlanViewModel
{
public string PlanID {get;set;}
}
or remove contentType: "application/json; charset=utf-8" and fix data
//contentType: "application/json; charset=utf-8",
data: { planID : planID },
in this case you don't need and extra class and frombody attribute. Leave your action header as it is

Passing parameter to MVC Action via Ajax always null

I looked at related questions to to form my ajax request but I can't figure out why this isn't working as the param is always null in the acion
I've done a console.log to check that item in 'data: { data: item }' has a value
//action
public async Task<IActionResult> DeleteMedia(string data)
{
$("#mediaTable").on('click', 'td:nth-child(7)', function () {
var item = $(this).parent().attr("id");
$("#MediaToDownload").val(item);
$.ajax({
url: '#Url.Action("DeleteMedia", "Home")',
type: 'get',
cache: false,
processData: false,
contentType: false,
data: { data: item },
success: function (data) {
location.href = data;
}
});
});
You need to send just the string, as JSON:
data: JSON.stringify(item)

Passing multiple objects to my controller

I am passing an object to my controller like so:
var form = JSON.stringify({
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val()
});
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
contentType: "application/json; charset=utf-8",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
my controller sees this as the object it is looking for:
public ActionResult CreateSubcontracts(RoutingSubcontracts s)
My problem is that I'd like to pass along just one more string. I know I can make a view specific model but I was wondering if I could do something like this for example:
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu)
I have tried the the following with no luck:
data: JSON.stringify({ "s": form, "bu": "251" }),
but the complex object just comes through as null. Is there a way I can pass the object and a string through as well?
Try adding the string item in the JSON you already have. Dont stringify it or it will just send a big string that youll have to parse again on the server.
var form = {
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val(),
"bu": "251" // add it here
};
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
In your view jquery create a second var for bu. Assign the data in you ajax call like this;
data: { "s" : form, "bu" : "251" }
In your controller method change the signature to include a default value for bu like this;
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu = "NoValue")
With the default value set bu will act like an optional parameter

.NET MVC 4 API Controller not getting AJAX data?

I have a simple ajax call that is not sending data correctly. What am I doing wrong? Here is the AJAX:
$.ajax({
url: '/api/Chat/New',
type: 'POST',
dataType: 'json',
data: { id : 10}
});
and here is my controller:
public class ChatController : BaseApiController
{
//
// GET: /Chat/
[HttpPost]
public int New(int id = -1)
{
return id;
}
}
BaseApiController is my own controller that has DB context in it and it inherits from ApiController. I cannot get data to send across the wire at all. New() just returns -1 every time.
try removing the data type from your ajax call. Something like this
$.ajax({
url: '#Url.Action("New", "Chat")',
type: 'post',
cache: false,
async: true,
data: { id: 10 },
success: function(result){
// do something if you want like alert('successful!');
}
});
try this
$.ajax({
url: '/api/Chat/New',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ id : 10})
});
Please take a look at the answer of the following post
http://forums.asp.net/t/1939759.aspx?Simple+post+to+Web+Api
Basically, Web API Post accept only one parameter, it can be a primitive type or a complex object.
Change your ajax request to the following
$.ajax({
url: '/api/Chat/New',
type: 'POST',
data: { '' : 10}
});
Then change your controller as follows
[HttpPost]
public int New([FromBody]int id = -1)
{
return id;
}
If it's a complex object like a ViewModel, you don't need to use FromBody
You can read more about why this is required by reading "Using[FromBody]" section in the following article.
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

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