Is it possible to store Ajax call as an object?

Rose

New Member
#1
This isn't necessarily a "how to" question, but rather an ask to help improve upon my own understanding of JavaScript and Jquery. I've been using Jquery a lot lately in my current job and all of my jquery involves a lot of AJAX calls. In several files I have at least 6 ajax calls for different situations and I was wondering if there was a more efficient way to do this from building the code. One of my colleagues who doesn't code suggested turning the AJAX call into a property and passing along arguments. Is this even possible? If not, is there a better and easier way to handle multiple AJAX calls in one file?

Thank you for your input and I hope to learn a lot from this

Here is an example of one of our AJAX calls
Mã:
$.ajax({
      type: 'POST',
      url: '',
      data: {
        method: 'custCodeData',
        custCode: $('#custCode').val()
      },
      dataType: 'JSON',
      success: function (data) {
        var array = data.DATA;
        $("#response tr:not(:first)").remove();
        for (var i = 0; i < array.length; i++) {
          var newRow = table.insertRow();
          for (var j = 0; j < array[i].length; j++) {
            if (j < 7) {
              var cell = newRow.insertCell(j);
              cell.innerHTML = array[i][j];
            }

            if (j === 0) {
              if (array[i][0] == false) {
                cell.innerHTML = "No";
              }
              if (array[i][0] == true) {
                cell.innerHTML = "Yes";
              }
            }

            if (j === 2) {
              if (array[i][8] == false) {
                cell.innerHTML = `<a href='/buying/quicklink/index.cfm?Passed_CustomerID=${array[i][7]}'>${array[i][2]}     </a><i class="fa fa-arrow-down" aria-hidden="true" ONMOUSEOVER="return overlib('Incomming Customer', FGCOLOR, 'FFFFCC',  BORDER, 2, BGCOLOR, '000000', TEXTFONTCLASS, 'RollOver', WRAP);" ONMOUSEOUT="nd();"></i>`
              } else if (array[i][8] = true) {
                cell.innerHTML = `<a href='/buying/quicklink/index.cfm?Passed_CustomerID=${array[i][7]}'>${array[i][2]}         </a><i class="fa fa-arrow-up" aria-hidden="true" ONMOUSEOVER="return overlib('Outgoing Customer', FGCOLOR, 'FFFFCC',  BORDER, 2, BGCOLOR, '000000', TEXTFONTCLASS, 'RollOver', WRAP);" ONMOUSEOUT="nd();"></i>`
              }
            }
          }
        }
        $("#response tr:contains(Yes)").css({"background-color": "#ff0000", "color": "#FFF"});
      }
    })
 

Admin

Administrator
Thành viên BQT
#2
You try
Mã:
function doTheSameExactAJAXThingAgain(method){
    $.ajax({
      type: 'POST',
      url: '',
      data: {
        method: method,//<- METHOD here
        custCode: $('#custCode').val()
      },
      dataType: 'JSON',
      //...etc
}

doTheSameExactAJAXThingAgain('custCodeData');
doTheSameExactAJAXThingAgain('compNameData');
//etc.
 
Top