3

How can we emulate the timeout of $.ajax using $.post?

  • $.post boils down to $.ajax at the end of the day, so it's the same thing? There's no overload for $.post that allows for the timeout parameter though, so you'd need to use $.ajax - potentially this setting could be set in a $.ajaxSetup instead? - api.jquery.com/jQuery.ajaxSetup – SpaceBison Apr 4 '12 at 10:39
  • Why do you need to use $.post instead of $.ajax? If you must, you can set a global timeout for all requests using $.ajaxSetup({'timeout': ...}). – pjumble Apr 4 '12 at 10:40
5

$.POST is a preset version of $.ajax, so few parameter are already set.

As a matter of fact, a $.post is equal to

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

But, you can create your own post function to send the request through $.ajax at last.

Here is a custom POST plugin I just coded.

(function( $ ){
  $.myPOST = function( url, data, success, timeout ) {      
    var settings = {
      type : "POST", //predefine request type to POST
      'url'  : url,
      'data' : data,
      'success' : success,
      'timeout' : timeout
    };
    $.ajax(settings)
  };
})( jQuery );

Now the custom POST function is ready

Usage:

$.myPOST(
    "test.php", 
    { 
      'data' : 'value'
    }, 
    function(data) { },
    5000 // this is the timeout   
);

Enjoy :)

| improve this answer | |
  • Will this not spawn multiple calls to the script and cause a new dataset to be generated with each call? – Anriëtte Myburgh Nov 30 '17 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.