Meru
Meru

Reputation: 1595

javascript function with parameters in function-call possible?

Does following call make sense / is it even possible?

    getCall('GET', URL, null, function(x, status, jqXHR){ }, failedRes);



     function getCall(method, url, data, func, func2){
        .ajax({
            type: method,
            contentType: "application/json",
            data: data,
            url: url,
            dataType: "json"
          }).done(function(data, textStatus,jqXHR) {
                console.log("done");
            }).fail(function(jqXHR, textStatus, err){
                console.log("fail");
            });
   } 

    function func2(jqXHR, textStatus, errorThrown){
        window.alert("AJAX call error occured");
        console.error( errorThrown );
    }

I wonder most because of the "{}", but also because of the parameters. Is the function-parameter "function(data, textStatus, jqXHR){ }" too much? Rather the {} not correct?

Upvotes: 0

Views: 72

Answers (4)

StackSlave
StackSlave

Reputation: 10617

This is JavaScript AJAX request/response format:

function xhr(method, url, send, success){
  var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
  var v = send ? encodeURI(send) : null;
  method = method.toUpperCase();
  x.open(method, url);
  if(method.match(/^POST$/)){
    x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    x.setRequestHeader('Content-length', v.length); x.setRequestHeader('Connection', 'close');
  }
  x.onreadystatechange = function(){
    if(x.readyState === 4 && x.status === 200){
      success(x.responseText);
    }
  }
  x.send(v);
}

Upvotes: 0

Philipp
Philipp

Reputation: 69693

function(x, status, jqXHR){ } defines a function which can be called, but when it is called it doesn't do anything except returning undefined. In some situation, this might be intentional.

In this case I wonder why that parameter exists at all, because getCall doesn't even use the parameter func.

Upvotes: 1

jabbink
jabbink

Reputation: 1291

Yes, this works.

function callFunction(func, param) {
    return func(param);
}
callFunction(
    function(a) {
        return a*2;
    },
    2
);

returns 4

Upvotes: 0

james emanon
james emanon

Reputation: 11807

You can pass anything in. Personally, I like to set up data passing in a more structured manner just in case, in the future, things need to be updated. Passing function references or functions themselves is totally doable.

ala:

var data = {
   call: "GET",
   url: URL,
   data: null,
   func: function(x, status,jqXHR){},
   func2: failedRes
}

getCall(data);


function getCall(data){
   data = data || {};

   // then just access your vars like so: data.url

Upvotes: 0

Related Questions