Kevin Kevin - 1 year ago 125
Ajax Question

Append Data to PJAX Request

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" }];


$('#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!

Answer Source

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) {
    type: 'POST',
    url: $(this).href,
    container: '#content',
    data: people,
    dataType: 'application/json'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download