1

Is there a reason why I should use

syntax 1

$.ajax({
  url: url,
  data: {foo: "foo", bar: 1},            // everything is declared
  success: success,
  dataType: dataType
});

And not syntax 2

$.ajax({
  url: url,
  data: {foo: valueOfFoo(), bar: calculateBar(100)},    // reference to functions
  success: success,
  dataType: dataType
});

When sending objects to a controller?

The jQuery API definition says that the type of data can be an object or a string that is sent to the server with the request.

Somehow I think that syntax 1 is "safer", but this might be superstition (paired with my experience from countless hours of bugfixing) and I can not be sure about it.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
witefox
  • 53
  • 4

1 Answers1

1

IMO There's no difference in term of sending objects to a controller the sended data will be the same in the both cases.

In term of clearness the first approach seems to be the cleaner one, because you just define the data object properly without calling the functions and doing extra process during definition when those calls could be done before this part and they doesn't have no needs to call them inside $.ajax.

If you should really to call some function you could call them like :

var foo = valueOfFoo();
var bar = calculateBar(100);

$.ajax({
    url: url,
    data: {foo: foo, bar: bar},
    success: success,
    dataType: dataType
});

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 1
    It is clearer, I think so too. Do you know any source where I can read how the data-object is generated (e.g. before it is sent to the controller)? – witefox Jan 13 '17 at 16:14
  • I'm sorry not sure what you mean :( but the data will be sent according to the HTTP Request Methods, the two `"POST", "GET"` are the commonly used methods for a request-response between a client and server.. you could find how every one of this methods works in http://stackoverflow.com/questions/504947/when-should-i-use-get-or-post-method-whats-the-difference-between-them – Zakaria Acharki Jan 13 '17 at 16:31