Bug Tracker

Ticket #3387 (closed feature: worksforme)

Opened 6 years ago

Last modified 5 years ago

In $.ajaxSetup, set data to always be passed in ajax requests

Reported by: dalangalma Owned by:
Priority: major Milestone: 1.3
Component: ajax Version: 1.2.6
Keywords: Cc:
Blocking: Blocked by:

Description

In $.ajaxSetup you can set the data parameter, but that's just a default that always gets overwritten with your own data. What I'd like is the ability to set default data that gets merged ($.extend-style) into whatever data I put in specific ajax requests. This would enable things like inserting the current user's name in every AJAX request, or automatically including Rails' authenticity_token.

I know that you can hack around this by attaching to $.ajaxSend and directly messing with the XHR, but that's messy.

Change History

comment:1 Changed 6 years ago by flesler

  • Status changed from new to closed
  • Resolution set to invalid

You can do that within beforeSend. This is not really something useful for the common user.

comment:2 Changed 6 years ago by dalangalma

  • Status changed from closed to reopened
  • Resolution invalid deleted

Man, I wish trac would email me when tickets get updated. So I might be missing something, but looking at the code, beforeSend (and ajaxSend) is triggered after data is serialized, so I can't do this on beforeSend. Anyway, I want this to be global to all ajax requests, and not have to do it each time - if I wanted to do it each time I'd just add the data anyway. I also don't think you can modify the ajax settings in those events.

I don't think this is not useful for the common user - anyone who wants to send some piece of data with every request, such as the Rails authenticity token, or adding in some profiling data or something, would want this method.

comment:3 Changed 6 years ago by dalangalma

Actually, you're probably right - this doesn't have wide appeal. You can't do it with beforeSend though. I've done it by making a plugin that wraps $.ajax to always pass some specific data.

comment:4 Changed 6 years ago by snobojohan

I think this will have a wide appeal since alot of us nowadays creates ajax that fails gracefully and has fallbacks for non javascript users. If I submit a form with Ajax submit I wan't to add for example ajax=true to the get or post. So that the action page can adapt it's output depening of how it was submitted.

comment:5 Changed 5 years ago by john

  • Status changed from reopened to closed
  • Resolution set to worksforme

Actually this overriding doesn't seem to happen anymore (or, at least, hasn't for quite a while). A deep copy of the Ajax settings is done so the original data stays intact.

You should be able to do $.ajaxSetup({ data: ...your data... }); and have it be copied in just fine.

In fact we even have unit tests that cover that use case.

Note: See TracTickets for help on using tickets.