Jquery Pjax - Ajax Success Function

I am currently translating my ajax calls for a regular call to $.pjax() . Everything works fine, but the success function is ajax. I cannot control how to call the pjax success function with the given parameters.

The only thing I can use is to define the pjax global success function that will be called every time pjax is called:

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

But, unfortunately, I would like to define a specific success function for each call.

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!')} }); 
+7
javascript jquery ajax pjax
source share
2 answers

I do not believe jQuery PJAX library supports passing the success function directly to the $ .pjax call, although I suspect you can get around this with the $(document).on('pjax:success') and its attribute options in to achieve the same functionality.

For example, let's say your query is similar to the one above, but you want to have a custom success callback, you can use something like this:

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

Then, to run the custom_success method, you can attach a standard pjax success listener and, given that all the parameters provided by $.pjax become available in the parameters, you can capture the custom_success function and run it. So your listener might look something like an 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(); } }); 

What * think * will I give you the functionality after?

+11
source share

Late answer, but I found a solution here .

 $.pjax({ url:"/myPage/myFunction", type:"POST", container:'#right_form', data:giveMeData(), }).done(function() { console.log('Success works!') }); 
+3
source share

All Articles