Add data to PJAX request

I use PJAX and it works great for simple examples, but I need to do some advanced tasks with PJAX requests.

  • I would like to add some data to every PJAX request. The data I want to add is actually an array of objects. See the example below.
  • I may need to use POST instead of GET to call ajax.
  • I may need to change the content type to "application / json".

I have the following ...

var people = [{ first: "John", last: "Doe" }, { first: "Jane", last: "Smith" }]; $("a.sheet-link").pjax("#content"); $('#content').on('pjax:beforeSend', function (e, jqXHR, settings) { // Modify ajax request here? // Would like to append the people array to data // Would like to POST rather than GET // May need to change content-type to "application/json". }); 

I tried various approaches ...

  • using jQuery.ajaxSetup to set some default values ​​(I can set the data, but then the _pjax data item was not added, I tried to set the POST type, but it wasn’t.)
  • trying to change jqXHR object in beforeSend handler
  • trying to change the settings object in the beforeSend handler

All attempts give me various problems.

I'm not sure why this is so complicated. Any help would be greatly appreciated!

+8
ajax pjax
source share
1 answer

Because the documentation indicates:

You can also just call $ .pjax directly. It acts the same as $ .ajax, even returning the same thing, and accepts the same options.

I would try the following:

 var people = [{ first: "John", last: "Doe" }, { first: "Jane", last: "Smith" }]; $('a.sheetlink').click(function(e) { e.preventDefault(); $.pjax({ type: 'POST', url: $(this).href, container: '#content', data: people, dataType: 'application/json' }) }); 
+7
source share

All Articles