Doug Null
Doug Null

Reputation: 8327

how to get data from .load immediately

How can I get the data read using .load immediately into a JavaScript variable?

When I use .load in a JavaScript function, to read an element from the server to an element in the browser page, if I immediately read the browser page element, then it has not updated yet.

The next time my function runs, then the browser page element is up to date.

Below, the variable latest_MM is not up to date until process_MM_button() is called again.

    function process_MM_button() {
        $('#result').load('_wm_load3.html #MM_upload_status_windmark_field_id');

        var latest_MM = document.getElementById("result").innerHTML
}

enter code here

Upvotes: 0

Views: 455

Answers (1)

Jasper
Jasper

Reputation: 75993

You can use the callback function of the .load() function:

function process_MM_button() {
    $('#result').load('_wm_load3.html #MM_upload_status_windmark_field_id', function () {
        var latest_MM = document.getElementById("result").innerHTML;

        //or using jQuery
        var latest_MM = $("#result").html();
    });
}

Using the callback function for the .load() function will allow the server response to be added to the DOM before trying to get the #result element's HTML.

Docs for .load(): http://api.jquery.com/load/

You could also use one of the other AJAX functions to store the data returned from the server before adding it to the DOM:

function process_MM_button() {

    //create AJAX request
    $.get('_wm_load3.html', function (serverResponse) {

        //turn serverResponse variable into jQuery object (was most likely a string) and then limit it to the desired element
        serverResponse = $(serverResponse).find('#MM_upload_status_windmark_field_id');
        var latest_MM = serverResponse;

        //add the server response to the DOM
        $('#result').html(serverResponse);
    });
}

Upvotes: 1

Related Questions