0
                $('form[name=addform]').submit(function() {
                    if(error == true){
                        return false;
                    }else{


                        $('#loading').empty();
                        $('#loading').append("<img src = './images/ajax-loader.gif'/>");
                        $('#loading').show();

                        setTimeout(function(){
                              return true;
                        }, 4000);


                    }
                    error = false;
                });

i need to load gif image before executes the return true. i do not use ajax for this please help

Perry
  • 11,172
  • 2
  • 27
  • 37

2 Answers2

3

I'm not exactly sure what you are trying to accomplish, but that code won't work. setTimeout() does not pause the function it has been called from, nor does the return statement in the callback affect it.

  • is their any alternative codes that i can use? how can i load a gif image befofe it executes the return statement? pls help. – user2595051 Jul 18 '13 at 10:37
  • So you want to make sure the loader image is shown before submitting the form? I suppose the easiest way would be to have the image pre-loaded in your DOM. Then you only have to set it to visible, which is instantly. You also avoid making your user wait 4 seconds before his request is processed, which I don't think is a good idea. – Ulrich Schmidt-Goertz Jul 18 '13 at 10:59
0

JavaScript is asynchronous, not synchronous - setTimeout will not 'block' the execution of the next line of code. (See related What is the difference between synchronous and asynchronous programming (in node.js))

To submit the form after a delay (for what purpose is unclear) you will first need to stop the form submitting (by cancelling the event) then submit the form once again as when setTimeout callback is executed.

$('form').on('submit', function(event) {

  // Prevent the form from submitting
  event.preventDefault();

  // 'this' is referring to the event target
  var form = this;

  // It may not be required to wrap the `form.submit` method but it's usually safer to do so
  setTimeout(function() {
    form.submit()
  }, 4000);

});

Here is an example http://jsfiddle.net/xppNp/1/

Community
  • 1
  • 1
i_like_robots
  • 2,760
  • 2
  • 19
  • 23