$.ajax method not calling the controller action method - javascript

I am calling javascript function on #Html.ActionLink clicked event. The Javascript function calls the jquery function in which I have written the $.ajax method for calling the json controller method. But it is not calling the controller method.......
Here is my code:
View
#Html.ActionLink("Submit", "AdminEvaluate", "Application", new { onclick = "Show('" + Model.applicationList.ApplicationId + "','statusList')" })|
Here, ApplicationId is coming from database and statusList is Radio Button group name from where I need to find the selected radio button.
Javascipt and jQuery code
function Show(appId, appStatus) {
$.fn.gotof(appId,appStatus);
}
Getting parameter from view and passing to jQuery function
jQuery function
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/Application/UpdateApplicantStatus',
data: { id: appId , status: selectedItem},
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
Controller Method
public JsonResult UpdateApplicantStatus(int id, string status){
return Json("Correct", JsonRequestBehavior.AllowGet);
}
I have put break point on controller method but it is not coming at a break point.
Thanks in Advance.

May be this sample help you :) let me know
ajax call with type :
$.ajax({
type: "GET",
url: '#Url.Action("UpdateApplicantStatus", "Application")',
contentType: "application/json; charset=utf-8",
data: { id: appId , status: selectedItem },
dataType: "json",
success: function() { alert('Success'); }
});
controller :
public ActionResult UpdateApplicantStatus(int id, string status){
return Json(// blah blah blah ...
}
This should work else let me know

Your ajax call is wrong.
If your controller method signature is
public JsonResult UpdateApplicantStatus(int id, string appStatus)
Then you MUST have parameter names matching with your parameters of your ajax call.
So, instead of
data: { id: appId , status: selectedItem}
Just write
data: { id: appId , appStatus: selectedItem}
If you have any other problem, just post the error(s) you should have in your browser's console.

Maybe parameter names of controller function and ajax calling function should match.
you can try this
data: { id: appId , appStatus: selectedItem},

Do that way actually 3 mistakes 1 was notify by #Mr Code the type is missing 2nd your parameters not match as your function takes one you send the data in wrong format..
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/ApplicationController/UpdateApplicantStatus',
data:"{'id':'" + appId + "', 'appStatus': '" + selectedItem+ "'}",//here you format is wrong i correct it
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});

sat on this for hours:
When using ajax - json in a js.script file:
the url is written with its real path e.g. - url: '/contoller/Action',
$.ajax({
url: '/NextPage/GetSpDropDown',
data: {'segInputVal': segInputVal},
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;.....
If the script is written in your HTML page then you must use
#(Url.Action(Action,controller))
$.ajax({
url: "#(Url.Action("GetSpDropDown", "NextPage"))",
data: { 'segInputVal': segInputVal },
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;....
And dont forget not to include the word controller in your controller name.
I have had SO MUCH help from stackoverflow- hope to pay a little back

Related

AJAX post data is null when it reaches the ASP.NET Core 2.1.1 controller

I have a problem posting a value from java-script in my razor page to a controller. - the value received is always null.
I have seen similar questions being asked, but have not been able to find the right solution to the problem.
I get to a break point in the controller, (so the routing is okay) but the parameter value passed is always null, and not being the sharpest in java-script, I would like some tips from you folks.
I basically have the java-script below:
var clickButton = function (buttonId) {
$.ajax({
type: "POST",
async: false,
cache: false,
crossDomain: false,
contentType: "application/json; charset=utf-8",
url: "v1/buttons",
dataType: "json",
data: '{ buttonId:'+JSON.stringify( "buttonId" ) + '}',
success: function (result) {
//console.log("clickButton OK => " + result);
}, //success: function (result) {
timeout: 500 // 0.5 sec.
}); //$.ajax({
}//var clickButton = function(buttonNo) {
and the C# controller code below too:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult OnButtonClicked( string buttonId )
{
// buttonId = null !!!
...
I have a similar problem getting a boolean value across to another controller.
where the bool is always false.. i.e. the default value.
I am wondering if it is a security issue, with not allowing the post to contain data, when the user is unauthorized...
The problem was in the JSON, and I got the value through with this minor change, but it was hiding well.
var clickButton = function (buttonNo) {
console.log("clicked: " + buttonNo);
$.ajax({
type: "POST",
url: "v1/buttons/",
dataType: "json",
data: { "buttonId": buttonNo }, // < === this is where the problem was !!
success: function (result) {
}, //success: function (result) {
}); //$.ajax({
}//var clickButton = function(buttonNo) {
I've changed the controller to receive a string to id the button.
And it now looks like this:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult PostButtonClick( string buttonId ) {
// buttonId now has a value !!!
}
}

How to pass string array to controller using ajax?

// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

AJAX GET returns undefined on the first call, but works on the second one

I am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);

Jquery AJAX CALL with parameter to controller's method not working

I am working with Jquery AJAX Call in MVC Application. My view looks like this :
<p>
Name #Html.TextBox("Name")
Date #Html.TextBox("Date")
<input type="submit" id="SubmitName" value="Submit" />
</p>
My AJAX call is as follows :
<script type="text/javascript">
function send() {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
$("SubmitName").click(function () {
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
},
});
})
}
</script>
And my controller looks like this :
[HttpPost]
public ActionResult Details (string StudentName, string DateofJoining)
{
var result = (from dc in _db.Details
where dc.Name== StudentName
select dc.Address);
return Json(result, JsonRequestBehavior.AllowGet);
}
I don't know what I'm missing. The ajax request is not working. Could anyone help me with this ?
Imagining that ur controller name is DQR then you need to write as below:-
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
},
});
and id should be:-
$("#SubmitName").click(function () {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
//// your ajax call
}});
and what is Send()? i mean the click event should be under $(document).ready(function() {});
I would suggest take simple button rather than "submit" if you are playing client side with that.
Bind click handler properly, move Details object creation in click handler
$(function() {
$("#SubmitName").click(function () {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
}
});
});
});
You can use jQuery $.post method as well.
Here is an example.
var StudentName = $("#Name").val();
var DateofJoining = $("#Date").val();
$.post('/Controller/Action', { 'StudentName': StudentName , 'DateofJoining': DateofJoining }, function(data) {
$('#target').html(data.msg);
}, 'json');
Here is more information about $.post

Categories

Resources