Jquery Pjax - Ajax success function
Asked Answered
P

2

16

Currently I am translating my ajax calls to regular $.pjax() call. Everything works fine but ajax success function. I can't manage how to call pjax success function with given parameters.

The only thing I can use is defining pjax global success function to be called on each pjax call:

   $(document).on('pjax:success', function(event, data, status, xhr, options) {

   });

But unfortunately I would like to define per call specific success function.

Ajax call example:

 $.ajax({
    url:"/myPage/myFunction",
    type:"POST",
    data:giveMeData(),
    success:function(data){$('#right_form').html(data);console.log('Success works!')}
 });

Pjax call example:

 $.pjax({
    url:"/myPage/myFunction",
    type:"POST",
    container:'#right_form',
    data:giveMeData(),
    success:function(){console.log('Success works!')}
 });
Physicalism answered 10/2, 2014 at 14:19 Comment(0)
H
13

I don't believe that the jQuery PJAX library supports passing a "success" function directly in to a $.pjax call, although I suspect you could work around this using the $(document).on('pjax:success') callback & its options attribute in order to achieve the same functionality.

For example, say your request is like the above, but you want to have a custom success callback you could use something like this:

 $.pjax({
    url:"/myPage/myFunction",
    type:"POST",
    container:'#right_form',
    data:giveMeData(),
    custom_success:function(){console.log('Custom success works!')}
 });

Then, in order to run the custom_success method you could hook up the standard pjax success listener, and given that all the parameters provided to $.pjax are made available in options, you can then grab custom_success function and run it. So your listener may look something like example

 $('#right_form').on('pjax:success', function(event, data, status, xhr, options) {
      // run "custom_success" method passed to PJAX if it exists
      if(typeof options.custom_success === 'function'){
           options.custom_success();
      }
 });

Which i *think* would provide the sort of functionality your after?

Hamster answered 10/2, 2014 at 21:54 Comment(2)
Yes, this is excactly what I was looking for. Other solution might be also using ".done(function(){console.log()})" postfix to each pjax call, but it doesnt apply on success listener probably. One big "thank you" again :)Physicalism
can anyone help me with this question? #49123472Myrtia
M
7

A late answer but I found the solution here.

$.pjax({
    url:"/myPage/myFunction",
    type:"POST",
    container:'#right_form',
    data:giveMeData(),        
 }).done(function() { console.log('Success works!') });
Marvismarwin answered 25/11, 2015 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.