Vahid Kharazi
Vahid Kharazi

Reputation: 6033

run a javascript function before other function

I have this code:

var is_recorded_book; 
function callback(data){

  is_recorded_book = data.result
  alert(is_recorded_book)

}

function check_book(){
  Dajaxice.darkoob.migration.is_book(callback, {'book_title': $('#id_book_title').val() })
  alert ("check book" +is_recorded_book);
  if (is_recorded_book){
    return true;
  }else{
    return false;
  }
}
</script>

and a have a form like this:

        <form action="..." method='...' onsubmit='return check_book()'>
...
          <input type='submit' />

but my output is: alert ("check book" +is_recorded_book); alert (is_recorded_book)

but i want run alert(is_recorded_book) at first.

i edit my check_book function to:

function check_book(){
    Dajaxice.darkoob.migration.is_book(function(data){
    callback(data);
    alert('dfsdf')
    if (is_recorded_book){
      return true;
    }else{
      return false;
    }
  }, {'book_title': $('#id_book_title').val() })
}

but alert('dfsdf') not work.

Upvotes: 0

Views: 102

Answers (2)

Jan Turoň
Jan Turoň

Reputation: 32922

This is how your check_book works:

  1. you make an asynchronous http request: this means that the request is sent and waits for the server to respond
  2. meanwhile the alert check_book is displayed and the function returns false, since isRecorder_book is still undefined
  3. after some time, when the server responds, the callback runs and sets the is_recorder_book (too late)

There are some workarounds

  1. either use synchronous http request (set the third parameter to false in open method).

  2. Or submit the form by the callback after setting the is_recorder_book

The code for the second option:

var is_recorded_book = false; 
function callback(data) {
  is_recorded_book = data.result;
  alert(is_recorded_book);
  alert("check book" +is_recorded_book);
  document.getElementById("yourform").submit();
}

function check_book(){
  Dajaxice.darkoob.migration.is_book(
    callback, {'book_title': $('#id_book_title').val() }
  );
}

<form id="yourform" onsubmit="check_book(); return is_recorder_book;">

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

You need to execute the alert inside the callback:

Dajaxice.darkoob.migration.is_book(function (data) {
    callback(data);
    alert("check book" +is_recorded_book);
}, {'book_title': $('#id_book_title').val() });

Upvotes: 2

Related Questions