Append Data to PJAX Request
Asked Answered
C

1

8

I am using PJAX and it is working great for simple examples, but I need to be able to do a few advanced things with the PJAX requests.

  1. I would like to append some data to each PJAX request. The data I want to append is actually an array of objects. See example below.
  2. I may need to use POST rather than GET for the ajax call.
  3. 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 have tried a variety of approaches...

  • using the jQuery.ajaxSetup to set some default values (I can set data, but then the _pjax data element is not appended; I tried to set the type to POST, but that did not stick.)
  • trying to modify the jqXHR object in the beforeSend handler
  • trying to modify the settings object in the beforeSend handler

All attempts give me various issues.

I am not sure why this is so difficult. Any help would be greatly appreciated!

Cavie answered 21/4, 2012 at 15:59 Comment(0)
Y
7

Since the documentation points out:

You can also just call $.pjax directly. It acts much like $.ajax, even returning the same thing and accepting 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'
  })
});
Yautia answered 30/4, 2012 at 23:38 Comment(1)
Thanks. That is the approach I ended up taking.Cavie

© 2022 - 2024 — McMap. All rights reserved.