0

usually when I need to use the same function with some edits I must copy/paste the function and then add some variables (sometimes the code is very long)

for example: 1st f unction

                $.ajax({
                type: 'GET',
                url: url,
                data: {s: size},
                dataType: 'json',
                success: function (data) {
                //data

In the second function i have to add a variable in data (success data will be the same as the first function):

                $.ajax({
                type: 'GET',
                url: url,
                data: {s: size, f:from},
                dataType: 'json',
                success: function (data) {
                //data

How I can call the first function without rewrite all?

Lib3r74
  • 1
  • 4

2 Answers2

2

You can have an function and pass the data into it and call your $ajax inside the function with the given data. Also you can pass your callbacks into it to make more flexible.

function makeAjax(data, success, error){
   $.ajax({
          type: 'GET',
          url: url,
          data: data,
          dataType: 'json',
          success: success,
          error: error
       });
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

Enclose your AJAX request in a single function and pass your data as a parameter.

function ajax_request(request_data) {
    $.ajax({
        type: 'GET',
        url: url,
        data: request_data,
        dataType: 'json',
        success: function (data) {
             //do something here
        }
    });
}
Deepansh Sachdeva
  • 1,168
  • 9
  • 16