April 4, 2012

Timeout in Jquery $.post by emulating $.ajax

Question by newbie

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

Answer by Starx

$.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 🙂

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!