4

Does the jQuery $.ajaxSetup method not respect the data field in the options hash when $.post or $.get is called?

For example, I might have this code:

$.ajaxSetup({ data: { persist: true } });

Then, to send a POST request, I would call this:

$.post("/create/something", { name: "foo" });

I was expecting the actual POST data to look like this:

{
  persist: true,
  name: "foo"
}

but the only data sent by $.post is { name: "foo" }. Is there any way to get the expected behavior? I'm using jQuery 1.4.1.

Sumurai8
  • 19,483
  • 10
  • 67
  • 96
Justin Poliey
  • 16,269
  • 7
  • 36
  • 48

2 Answers2

6

$.ajaxSetup() sets defaults for your ajax requests. Any options you set in the request method will override these defaults, not merge them. You're actually overriding

{ persist: true }

with

{ name: "foo" }


This no longer appears to be the case — a ticket on the jQuery tracker suggests that this was added in a version update and jQuery now merges the objects instead of replacing the default (thanks @Quincy).
Andy E
  • 326,646
  • 82
  • 467
  • 441
  • 2
    Although this question is a year old, the merge is working now. Just comment here in case of anyone reading this. @see http://bugs.jquery.com/ticket/3387 – Quincy Jul 13 '11 at 06:26
  • I've tried merging a post parameter in ajaxSetup with data using serializeArray but this overrides the parameter defined in axaxSetup http://stackoverflow.com/questions/21501224/define-global-ajax-post-param-and-merge-with-different-requests – Asa Carter Feb 01 '14 at 20:45
0

As documentation says data option is converted to query string and appended to the URL for GET requests.

RaYell
  • 68,096
  • 20
  • 124
  • 150
  • I think the documentation is unclear here. For a POST request, `data` should be converted to a query string and sent via the POST body. – Andy E Mar 30 '10 at 07:42