0

Total noob question but say if created a function called sendRequest that takes in a couple of parameters for an ajax call.

The ajax request isnt that necessary, most wanted to know about the parameters.

function sendRequest($el, url, trackingUrl, actionTypeString) {
 $.ajax({
   method: 'POST',
   url: url,
   actionTrackingUrl: trackingUrl,
   actionType: actionTypeString,
   el: $el,
 })
}

function testCase1() {
  // ......... code
  this.sendRequest($someEl, url, someTrackingUrl, someActionTypeString)
}

function testCase2() {
  // .......code
  this.sendRequest($someEl, someUrl, someActionTypeString);
}

Where in testCase2 I want to fill the 4th parameter (actionTypeString) and not 3rd parameter?

Richard Bustos
  • 2,298
  • 3
  • 19
  • 30

2 Answers2

1

For testCase2, you would need to pass in a null parameter.

  this.sendRequest($someEl, someUrl, null, someActionTypeString);

If you want to have optional parameters, the commonly-used pattern in javascript is to pass in one object containing all of the parameters, named appropriately:

function sendRequest(options) {
 $.ajax({
   method: 'POST',
   url: options.url,
   actionTrackingUrl: options.trackingUrl,
   actionType: options.actionType,
   el: options.$el,
 })
}

function testCase1() {
  // ......... code
  this.sendRequest( {
         $el: $someEl,
         url: someUrl,
         trackingUrl: someTrackingUrl,
         actionType: someActionTypeString
  });
}

function testCase2() {
  // ......... code
  this.sendRequest( {
         $el: $someEl,
         url: someUrl,
         actionType: someActionTypeString
  });
}
Andrew Shepherd
  • 40,674
  • 26
  • 128
  • 192
0

Parameters are assigned to named arguments in order. If you want to pass the 4th but not the 3rd argument, you need to explicitly pass null.

function testCase2() {
  sendRequest($someEl, someUrl, null, someActionTypeString);
}

Additionally, I don't believe you are using this correctly - in this case it refers to the global object. You can just reference the function name.

Jonah Williams
  • 14,535
  • 4
  • 52
  • 48