Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Pjax - Ajax success function

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!')}
 });
like image 532
even2be Avatar asked Feb 10 '14 14:02

even2be


2 Answers

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?

like image 95
Carl Avatar answered Oct 23 '22 06:10

Carl


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!') });
like image 44
Coz Avatar answered Oct 23 '22 06:10

Coz