Ad

Reusable Ajax And Javascript Function In CSHTML(RAZOR)

- 1 answer

Im new in js and razor,part of my code should be repeated and this imposed more lines of code to my project,it could be nice if i can make it reusable,for example Ajax,where should i create a ajax to a specific URL to just call it when i need?in a separated razor file?in the following code,i have two click events and my ajax call and url is repeating,i want to get rid of this repeat:

function seriesClick(e) {
var _clicketBarChart = e.series.categoryField;

$.ajax({
           dataType: "json",
           type: "POST",
           url: "@Url.Action("faultstatistics","Dashbrd")",
           contentType: "application/json; charset=utf-8",
           data: JSON.stringify({ "name": _clicketBarChart }),
               success: function (result) {
              faultstatChart(result);
               }
});


      function changeEvent(e) {             
      var _clicketCellGrid = e.categoryCell;


          $.ajax({
           dataType: "json",
           type: "POST",
           url: "@Url.Action("faultstatistics","Dashbrd")",
           contentType: "application/json; charset=utf-8",
           data: JSON.stringify({"name": _clicketCellGrid }),
               success: function (result) {
           faultstatChart(result);
               }
});
      }
Ad

Answer

You have to create single method that can handle two situations, please refer to this example (based on your):

var ajaxHandler = function(targetName) {
  $.ajax({
    dataType: "json",
    type: "POST",
    url: "@Url.Action("faultstatistics","Dashbrd")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({"name": _clicketCellGrid }),
    success: function (result) {
      faultstatChart(result);
    }
  });
}

var seriesClick = function(e) {
  var targetName = e.series.categoryField;
  ajaxHandler(targetName);
}
var changeEvent = function(e) {
  var targetName = e.categoryCell;
  ajaxHandler(targetName);
}
Ad
source: stackoverflow.com
Ad