Reputation: 997
I am writing a method to delete a town via jQuery and Ajax. Here is my code:
<button class="btn btn-danger btn-sm" onClick="deleteTown(@item.TownId)"><i class="fa fa-trash"></i></button></a>
Delete Town method:
function deleteTown(townId) {
console.log(townId);
$.ajax({
type: "POST",
url: "/Tenant/DeleteTownCritera",
dataType: "json",
async : false,
data: { Id: townId, TenantId: @Request.QueryString["tenantId"] },
success: processDeleteTownResult()
});
}
Success method:
function processDeleteTownResult(data) {
console.log(data);
if(data.Success == 1)
{
$("#town" + townId).remove();
}
}
Controller:
[HttpPost]
public JsonResult DeleteTownCritera(CriteriaInput input)
{
TenantLogic logic = new TenantLogic();
var x = logic.DeleteTownCritera(input);
return Json(x, JsonRequestBehavior.AllowGet);
}
What's happening?
I have a breakpoint set on my controller.
Essentially, I hit my button which called deleteTown.
Console logs town id.
Console logs undefined.
Console errors: Uncaught TypeError: Cannot read property 'Success' of undefined.
The controller is then hit with the correct TownId and TenantId.
Any suggestions of why the success method is being terminated before the ajax call is?
Thanks, Dan
Upvotes: 0
Views: 58
Reputation: 72299
First get the response and then you need to call your function by passing this response as parameter:-
success: function(response){
processDeleteTownResult(response);
}
Upvotes: 2
Reputation: 2043
It's being called because you've included parenthesis here:
success: processDeleteTownResult()
Replace with this:
success: processDeleteTownResult
Or
success: function(response){processDeleteTownResult(response);}
(as suggested in comments)
Upvotes: 2