mrdaliri
mrdaliri

Reputation: 7338

when a function's work is completed

I'm using a jQuery plugin, it gets data from an url, fetches, calculates and writes some data in a div.

I want to copy this div contents to another div, when that functions do its work.

for example:

$("#div1").myfunction(); // it gets and calculates data and adds to #div1 . it needs 2-3 seconds to be done
var contents = $("#div1").html(); // when myfunction() done, copy contents
$("#div2").html(contents);

when i ran that code, i didn't have new contents in #div2.

Upvotes: 5

Views: 162

Answers (4)

Joseph Silber
Joseph Silber

Reputation: 219936

If you're the one writing the plugin, you should either hard-code it into the AJAX callback function, or allow for a callback function to be passed in with the options.

If you have no control over the plugin, you'll have to constantly query your div to see if it has been updated:

var oldHTML = $("#div1").html(),
    counter = 0;

$("#div1").myfunction();

copyHTML();

function copyHTML()
{
    var newHTML = $("#div1").html();

    // we don't want this function to run indefinitely
    if (++counter > 15) return;

    if (newHTML == oldHTML)
        setTimeout(copyHTML, 1000);
    else
        $("#div2").html(newHTML);
}

Upvotes: 0

Ilia Choly
Ilia Choly

Reputation: 18557

you need to have myfunction take a callback parameter which it executes once the request is done

function myfunction(cb)
    $.ajax({
        type: "get",
        url: "page.html",
        success: function(data){
            $("#div1").html(data);
            if(typeof cb === 'function') cb();
        }
    });
}

myfunction(function(){
    $("#div2").html($("#div1").html());
});

Upvotes: 5

rxgx
rxgx

Reputation: 5160

Ajax callbacks (such as success) will be deprecated in jQuery 1.8. Instead, you can use jQuery's deferred object to run (or undo) an action that requires one more conditions before it is performed.

var successFunction = function() {
  var contents = $("#div1").html();
  var newElement = $("<div id=div2></div>").html(contents);
  $("body").append(newElement);
}

var failedFunction = function() {
  // reset element or undo last change
  window.alert("Update Failed");
}


$.when(
  $.ajax(countParams),
  doCalculate()
).then(
  successFunction(),
  failedFunction()
);

Creating Responsive Applications Using jQuery Deferred and Promises

Upvotes: 1

karim79
karim79

Reputation: 342645

You will simply need to put this line:

$("#div2").html($("#div1").html());

into the success callback of the ajax code implemented in myFunction, to ensure that the operation happens once the client has received the response and inserted it into the DOM.

Upvotes: 2

Related Questions