简体   繁体   中英

Multiple ajax calls on every call update the variable

On my page I have an ajax script which has a chain of ajax calls nested inside each other's success function so that the next one executes. For example --

            $.ajax({
                data: {
                    action: 'polly_pros',
                    pollytext: text
                },
                type: 'post',
                url: polpro.ajax_url,
                cache: false,
                success: function(data) {
                    $('#player')[0].pause();
                    $('#player')[0].load();
                    var aud_dur = $('#aud_dur').val();
              // NEXT AJAX CALL                  
                    $.ajax({
                        data: {

On my form my hidden input --

<input type="hidden" name="aud_dur" id="aud_dur" value="" />

On my page to update my hidden input of the audio file whenever it is loaded, I use --

var Aud = $('#player');
var aud_dur = $('#aud_dur');
Aud[0].addEventListener('loadeddata', function() {
    aud_dur.val($('#player')[0].duration);
});

On my php script I'm trying to retrieve the value as so --

$aud_dur = $_POST['aud_dur'];

My hidden input updates fine on my form but the new value is not being sent back so that I can use it with the very next ajax call. Right now there doesn't seem to be any data being sent from the variable.

Any suggestions?

EDIT

My ajax code has several calls in it that are executed upon the success of the previous one.

The polly_pros ajax call creates an audio file and the following ajax call is suppose to get the audio duration from there, which I am also putting in a hidden input.

I can get the duration if the file is already there but if creating the file dynamically (like I need to do) I am unable to get the duration value.

This is my full ajax code (unrelated variables deleted to simplify) ---

jQuery(document).on('click', '#make-vid', function(e) {
    e.preventDefault();
    var aud_dur;
    var pollytext = $('#pollytext').val();
    var path = $('#path').val();
    var post_id = $('#post_id').val();
    // AJAX CALL
    $.ajax({
        url: vformpro.ajax_url,
        data: {
            action: 'vform_pros',
            post_id: post_id,
        },
        type: 'POST',
        success: function(data) {
            console.log(data);
            var audio = $("#player");
            var post_id = $("#post_id").val();
            var aud_dur = $("#aud_dur").val();
            var tune_dur = $("#tune_dur").val();

            // AJAX CALL
            $.ajax({
                data: {
                    action: 'polly_pros',
                    post_id: post_id
                },
                type: 'post',
                url: polpro.ajax_url,
                cache: false,
                success: function(data) {
                    console.log(data);
                    $('#player')[0].pause();
                    $('#player')[0].load(function() {

                        // HERE I AM TRYING TO GET THE AUDIO DURATION UPON SUCCESS OF THIS AJAX CALL SO // THAT I CAN PASS IT TO THE FOLLOWING AJAX CALL

                        var Aud = $('#player');
                        var aud_dur = $('#aud_dur');
                        Aud[0].addEventListener('loadeddata', function() {
                            aud_dur.val($('#player')[0].duration);
                            console.log(aud_dur);
                        });

                    });
                    // AJAX CALL
                    $.ajax({
                        data: {
                            action: 'mvid_pros',
                            post_id: post_id,
                            aud_dur: aud_dur,
                            tune_dur: tune_dur
                        },
                        type: 'post',
                        url: mvidpro.ajax_url,
                        cache: false,
                        success: function(data) {
                            console.log(data);
                            $("#video-preview")[0].pause();
                            $("#video-preview")[0].load();
                        },
                        error: function() {
                            $('.load-text').text('Error on making Video.');
                        }
                    });
                },
                error: function(data) {
                    console.log(data);
                },
            });
        }
    });
});

UPDATE

Here's a link to the full code (WIP) to give better context to my question.

(Updated answer)

I still believe that the main problem is likely with $('#player')[0].load(function() {...}) that you have as in this code.

I mean, if the element with the id of player is an audio element, then the function you provided to the load() method of that audio element would never get called. And note that $(selector).load() is different from $(selector)[0].load() — the 'selector' can be '#my_id' , '.my_class' , etc.

But anyway, please try this code which is an optimized version of the full version of your code.

You may not be able to simply compare your code with the optimized version; however, it shouldn't be too hard for you to spot the major changes such as I used a single form_data object instead of numerous variables, where form_data stores the form data that you send to your PHP script.

And in the optimized code, you'll find this code which performs the third AJAX request (with the action mvid_pros ):

function mvidPros() {
  var aud_dur = $('#player')[0].duration;
  console.log(aud_dur);

  // Set the value of the #aud_dur field.
  $("#aud_dur").val(aud_dur);

  // Initialize the data for the 'mvid_pros' AJAX call.
  var form_data = {
    action: 'mvid_pros',
    post_id: $("#post_id").val()
  };

  // Add input values to the data.
  form_data.songlink = $("#songlink").val();
  ...
  form_data.aud_dur = aud_dur;
  form_data.tune_dur = $("#tune_dur").val();
  ...

  $.ajax({
    'data': form_data,
    type: 'post',
    url: mvidpro.ajax_url,
    cache: false,
    //async:false,
    success: function(data) {
      console.log(data);
      ...
    },
    error: function() {
      $('.load-text').text('Error on making Video.');
    }
  });
}

And here's the code that calls the above function:

$('#player')[0].pause();
$('#player').one('loadeddata', mvidPros);
$('#player')[0].load();

You need to include your aud_dur value in your post data to the server. The form submit method isn't being called, you are doing an ajax request.

$.ajax({
    data: {
        action: 'polly_pros',
        pollytext: text,
        aud_dur : $('#aud_dur').val()
    },
.....

Change your data object to that to include it in your post values and you should see it being sent to your server. You can check what is actually sent by inspecting the network request in your browser's dev console.

Per your updated question, your next Ajax call is running before your aud_dur value is being assigned. Put your Ajax call inside the event handler after you assign the aud_dur variable

jQuery(document).on('click', '#make-vid', function(e) {
    e.preventDefault();
    var aud_dur;
    var pollytext = $('#pollytext').val();
    var path = $('#path').val();
    var post_id = $('#post_id').val();
    // AJAX CALL
    $.ajax({
        url: vformpro.ajax_url,
        data: {
            action: 'vform_pros',
            post_id: post_id,
        },
        type: 'POST',
        success: function(data) {
            console.log(data);
            var audio = $("#player");
            var post_id = $("#post_id").val();
            var aud_dur = $("#aud_dur").val();
            var tune_dur = $("#tune_dur").val();

            // AJAX CALL
            $.ajax({
                data: {
                    action: 'polly_pros',
                    post_id: post_id
                },
                type: 'post',
                url: polpro.ajax_url,
                cache: false,
                success: function(data) {
                    console.log(data);
                    $('#player')[0].pause();
                    $('#player')[0].load(function() {

                        // HERE I AM TRYING TO GET THE AUDIO DURATION UPON SUCCESS OF THIS AJAX CALL SO // THAT I CAN PASS IT TO THE FOLLOWING AJAX CALL

                        var Aud = $('#player');
                        var aud_dur = $('#aud_dur');
                        Aud[0].addEventListener('loadeddata', function() {
                            aud_dur.val($('#player')[0].duration);
                            console.log(aud_dur);
                            // AJAX CALL **MOVED**
                            $.ajax({
                                data: {
                                    action: 'mvid_pros',
                                    post_id: post_id,
                                    aud_dur: $('#aud_dur').val(),
                                    tune_dur: tune_dur
                                },
                                type: 'post',
                                url: mvidpro.ajax_url,
                                cache: false,
                                success: function(data) {
                                    console.log(data);
                                    $("#video-preview")[0].pause();
                                    $("#video-preview")[0].load();
                                },
                                error: function() {
                                    $('.load-text').text('Error on making Video.');
                                }
                            });
                        });

                    });


                },
                error: function(data) {
                    console.log(data);
                },
            });
        }
    });
});

You have issue with your code, properly refactor your code and you should be fine:

PS: I wasn't able to run the code so please make sure you properly scope your variables in order for code to work properly.

jQuery(document).on('click', '#make-vid', function(e) {
    e.preventDefault();
    var pollytext = $('#pollytext').val();
    var path = $('#path').val();
    var post_id = $('#post_id').val();
    var onAudioDataLoaded = function() {
        var aud_duration = $('#player')[0].duration;
        var tune_duration = $("#tune_dur").val();
        $('#aud_dur').val(duration);

        // AJAX CALL
        $.ajax({
            data: {
                action: 'mvid_pros',
                post_id: post_id,
                aud_dur: aud_duration,
                tune_dur: tune_duration
            },
            type: 'post',
            url: mvidpro.ajax_url,
            cache: false,
            success: onMvidProsSuccess,
            error: onMvidProsError
        });
    };
    var onMvidProsSuccess = function(data) {
        console.log(data);
        $("#video-preview")[0].pause();
        $("#video-preview")[0].load();
    };
    var onMvidProsError = function() {
        $('.load-text').text('Error on making Video.');
    };
    var onPolyProsError = function(data) {
        console.log(data);
    };
    var onPolyProsSuccess = function(data) {
        console.log(data);

        $('#player')[0].pause();
        $('#player')[0].load(function() {

            // HERE I AM TRYING TO GET THE AUDIO DURATION UPON SUCCESS OF THIS AJAX CALL SO // THAT I CAN PASS IT TO THE FOLLOWING AJAX CALL

            var Aud = $('#player');
            Aud[0].addEventListener('loadeddata', onAudioDataLoaded);
        });
    };
    var onFormPostSuccess = function(data) {
        console.log(data);
        // AJAX CALL
        $.ajax({
            data: {
                action: 'polly_pros',
                post_id: post_id
            },
            type: 'post',
            url: polpro.ajax_url,
            cache: false,
            success: onPolyProsSuccess,
            error: onPolyProsError
        });
    };
    // AJAX CALL
    $.ajax({
        url: vformpro.ajax_url,
        data: {
            action: 'vform_pros',
            post_id: post_id,
        },
        type: 'POST',
        success: onFormPostSuccess
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM