continue jQuery after mysql data has loaded

I am using jquery and php along with WordPress to access data from a mysql database.

I managed to retrieve that data but would like jquery to wait until all the data has been retrieved.

Read More

Below is the pertinent code segment.

Both alert commands display nothing because the data has not finished loading.

How can I re-code this?

jQuery(document).ready(function ($) {
    load_qs('foo');
    alert($(".all-qa-free").val());
    //////////////////////////////////////////////////////////////////////////
    function load_qs(data) {
        var data = {
            action: 'load_question_set',
            async: false,
            cache: false,
            qset_id: data
        };

        $.post(the_ajax_script.ajaxurl, data, function (response) {
            var mydb_data = $.parseJSON(response);
            $("#all-qa").val(mydb_data.qa);
            alert($(".all-qa-free").val());
            return;
        });
    }
});

Related posts

2 comments

  1. Ajax calls are asynchronous, while the JS executes synchronously. jQuery/JavaScript initiates the ajax calls and immediately goes to the next line for executing. It doesn’t wait for the response to come from the server.

    Solution:
    Do all the processing, which you want to do on server response in the callback function itself. In your case, in the below function:

    function(response) {         
        var mydb_data = $.parseJSON(response);
        $("#all-qa").val(mydb_data.qa);
      alert ($(".all-qa-free").val());  
        return; 
    }
    

    Otherwise you will keep facing this issue. Try putting alert in the callback function. It’ll definitely work.

    One more thing, you are putting value in id “#all-qa” and fetching data from “.all-qa-free”, please check if you are doing this right.


    HappyCoding

  2. You should set async: true in your ajax call.

    Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
    If you set async: true then that statement will begin it’s execution and next statement will be called regardless of whether the async statement has completed yet.

Comments are closed.