Oleg Pasko
Oleg Pasko

Reputation: 2911

JS: wait for method done inside of function

I'm not really familiar with JS and was confused with next task.

I have remote form, but before sent data I need to do some action (fill form input with data). This is my code:

$('.edit_slide').on('ajax:beforeSend', function(event, xhr, settings) {
    html2canvas($('.slide_canvas'), {
      onrendered:
        function(canvas) {
            var img = canvas.toDataURL("image/png");
            $('#slide_thumbnail').val(img);
        }
    });
}); 

Form ajax from: https://github.com/rails/jquery-ujs/wiki/ajax .

Next I need to create image from DIV with html2canvas (http://html2canvas.hertzen.com/documentation.html) and pass it to server.

But form sent first and html2canvas done after (form submited with blank #slide_thumbnail and fill it with data after).

If I put here alert('hello') istead of html2canvas, alert works first and it's waiting for I press 'Ok' and form submited after.

Is it possible to wait image was created and sent it after ?

Upvotes: 0

Views: 1309

Answers (2)

The Alpha
The Alpha

Reputation: 146191

This could be applied as well (DEMO) :

$("form").on('submit', function(e) {
    e.preventDefault(); // prevent form submission
    console.log('Submit Prevented...');

    // do stuf, i.e.
    html2canvas($('.slide_canvas'), {
        onrendered : function(canvas) {
            var img = canvas.toDataURL("image/png");
            $('#slide_thumbnail').val(img);

            // Submit using ajax
            $.ajax({
                type : 'post',
                url : 'your_url',
                data : { html : $('#slide_thumbnail').val() },
                success : function(data){
                    console.log('Data returned fron the server : ' + data);
                }
            });
        }
    });
});

Upvotes: 1

nycynik
nycynik

Reputation: 7541

Your issue is that html2canvas returns immediately, setting up the callback to be called later. The callback is called after the ajax call is finished.

Solutions:

  1. Have the form call html3canvas before ajax send, and then call the ajax send after the onrendered callback. ( this is javascript on the form )
  2. wait for the callback inside the ajax send function. (http://api.jquery.com/category/deferred-object/)

Upvotes: 0

Related Questions