How to set `data` attribute of Ajax request dynamically in javascript

1k Views Asked by At

I have javascript function that will be called from a few pages when Kendo.Button() is clicked.

This is a Kendo.Button():

@(Html.Kendo().Button()
                    .Name("btnSubmit")
                    .HtmlAttributes(new { type = "button", title= "Report1", url = "/Controller1/Method1/"  })
                    .Icon("k-icon k-i-file-txt")
                    .Content("View Details")
                    .Events(e => e.Click("ShowDetails"))

)

This button will have different number of parameters defined in .HtmlAttribute property depending on a page. One page will have 3 parameters another will have just one.

When the button is clicked on either page the following javascript will be called:

This is my JavaScript:

function ShowDetails() {
    var URL = this.element.attr("url")
    $('#win_wnd_title').text(this.element.attr("title"));
    $.ajax(
        {
            url: URL,
            type: 'post',
            dataType: "html",
            data: ?
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                var dialog = $("#win").data("kendoWindow");
                $("#dataWin").html(result);
                dialog.open();
                showLoaderPopup();
            }
        })
}

I need to set data attribute dynamically, so when the function is called from one page, I do not need to set parameters to data attribute. In another case I need to do that. So, it will be something like that in the function:

If (flag == 1) 
{
   var myData =  JSON.stringify({ ID: id, Amount: amount, Desc: desc });
}
else
{
   var myData = null 
}

Then in the function I set the data property for Ajax request:

$.ajax(
   {
      .
      .
      .
      data: myData 
   }
)

So, only on a particular Button, the parameters will be sent.

How can I do that, so I do not repeat the same Ajax logic twice just to change the data parameters?

1

There are 1 best solutions below

2
Kamil Folwarczny On

I would make it comment, however i dont have enought reputation for that.

I would approach it pretty much like you described. I would add another parameter to button:

Button()
  .Name("btnSubmit")
  .HtmlAttributes(new { type = "button", title= "Report1", url = "/Controller1/Method1/", sendData = "true" })
  .Icon("k-icon k-i-file-txt")
  .Content("View Details")
  .Events(e => e.Click("ShowDetails"))
)

And then create local variable with data based on that html parameter. Something like that:

function ShowDetails() {
    var URL = $(sender).data('url');
    var myData = null;

    if($(sender).data('sendData') == "true")
    {
        myData = JSON.stringify({ ID: id, Amount: amount, Desc: desc });
    }

    $.ajax(
    {
        ...

        data: myData
        success: function (result) {
        ...
        }
    })

Hope it helps