0

I have code like this. I try to do recursive callback function doWork. When I run this i got first response from ajax and in "nextWord" div I got my second word. But I can't do callback doWork function to get second response.

Do you have any suggest?

<script>

    function doWork() {
        $.ajax({
            type: "POST",
            url: "eu.php",
            data: { word: $('#nextWord').html()},
            dataType: 'json',
            success: function( msg ) {
                alert($('#nextWord').html());
                $( "#nextWord" ).html( msg.nextWord );
                $( "#query" ).html( msg.query );
                doWork();
                //doWork; --- I try and this
            },                  
        });
    }

    $(function() {
        doWork();
    });
</script>


<div id="nextWord">firstword</div>
<div id="query"></div>
  • possible duplicate of [Calling a javascript function recursively](http://stackoverflow.com/questions/7065120/calling-a-javascript-function-recursively) – Cerbrus Feb 05 '14 at 09:35

1 Answers1

0

You should use .then instead of a success callback for avoiding two handlers for the same thing.

<script>

function doWork() {
    $.ajax({
        type: "POST",
        url: "eu.php",
        data: { word: $('#nextWord').html()},
        dataType: 'json',
        success: function( msg ) {
            alert($('#nextWord').html());
            $( "#nextWord" ).html( msg.nextWord );
            $( "#query" ).html( msg.query );

        },                  
    }).then(function(data){
                doWork();
                 });
}

$(function() {
    doWork();
});

Meysam
  • 463
  • 5
  • 6