-1

I dont know how can explain, following code works

function DrawIrregularChartGrid() {
    $('#data_grid').datagrid({
        columns: [[{"field":"MeterID","title":"MeterID"},{"field":"ADateTime","title":"ADateTime"}]]
    });
}

but this one does not work, there is no error message, grid is loading but col names are null.

function DrawIrregularChartGrid() {
    $('#data_grid').datagrid({
        columns: [GetGridColumnNames()]
    });
}

GetGridColumnNames()

returns

[{"field":"MeterID","title":"MeterID"},{"field":"ADateTime","title":"ADateTime"}]

GetGridColumnNames function

function GetGridColumnNames() {

var cols = [];
var IrregularChartParams = InitializeChartParams();

// parametreleri json stringe cevir...
var chartParams = JSON.stringify(IrregularChartParams);

$.ajax({
    type: "POST",
    url: app_base_url + 'Graph/GetGridColumnNames',
    contentType: 'application/json; charset=utf-8',
    data: chartParams,
    success: function (result) {
        $.each(result, function (index, value) {
            cols.push(result);
        });
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    },
    beforeSend: function () {

    },
    complete: function () {
    }
});
return cols;
}

dataGrid column property type is object array. How can assign GetGridColumnNames returning object to columns property.

1 Answer 1

3

It doesn't work because your AJAX call is asynchronous, so cols is empty when the function returns.

You need to defer all subsequent operations until the success: call has finished. Better yet, remove the success: and error: handlers and use explicit deferred objects, i.e.:

function GetGridColumnNames() {
    return $.ajax(...).then(
        function(result) {
            // pre-process result and _return_ the desired array
            ...
            return cols;
        },
        function(xhr, ajaxOptions, thrownError) {
            // error handling
        },
    }
}

GetGridColumnNames().done(function(cols) {
    // use column names here
});

The .then call is being passed two callbacks - one to pre-process the returned JSON data, and the other to handle errors.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, beat me to it, but this has to be a duplicate of a billion questions just like it ?
the question might be a dup, the answer isn't ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.