Natasha Natasha - 1 year ago 68
reST (reStructuredText) Question

Unable to pass data from ajax function after doing async false

I create a rest service and now I'm trying to create a gui with the data. Right now, my index.html looks like this:

<!DOCTYPE html>
<meta charset="ISO-8859-1">
<script type="text/javascript" src=""></script>

<script type="text/javascript" src="loadingGrid.js"></script>
<script type="text/javascript" src="sortGrid.js"></script>
<script type="text/javascript" src="ag-grid-enterprise.js"></script>
<title>Insert title here</title>
<div id="myGrid" style="width: 100%; height: 71%;" class="ag-blue">

And my file1.js looks like this:

var rootURL = "http://localhost:8181/RestServiceProject/rest/WebService/getdata";
function findByName() {
type: 'GET',
url: rootURL,
dataType: "json",
async: false,
success: function(json){ return json; }
var columnDefs = [
{headerName: "CLIENT", field: "CLIENT_ACRONYM", width: 150, unSortIcon: true},
{headerName: "SYM", field: "SYM", width: 150, unSortIcon: true, filter: 'set'},


var gridOptions = {
columnDefs: columnDefs,
rowData: null,
enableSorting: true,
enableFilter: true,
enableColResize: true


// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);

// do http request to get our sample data - not using any framework to keep the example self contained.
// you will probably use a framework like JQuery, Angular or something else to do your HTTP calls.
var jsondata = findByName()
var json = JSON.parse(jsondata);

function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);

var parsedData = {
return Object.keys(obj).reduce(function(memo, key) {
var value = obj[key];
memo[key] = isNumeric(value) ? Number(value) : value;
return memo;
}, {})



So, when go to localhost:8181/RestServiceProject, it goes to
div. Then in file1.js I have made a jQuery ajax function, where I want to return data on success so I've made async: false, I'm calling the
function below in file1.js and saving the value returned in var json as
var json = findByName()
. But json variable is coming
. Why is this so?

Answer Source

You're returning from the callback function, that's not the same as returning from findByName(). You can do what you want by setting a variable in the callback function and then returning that from the containing function.

function findByName() {
    var returnVal;
        type: 'GET',
        url: rootURL,
        dataType: "json",
        async: false,
        success: function(json){  returnVal = json;    }
    return returnVal;

However, it would be better if you designed your application so it worked with asynchronous AJAX. Synchronous AJAX is deprecated. See How do I return the response from an asynchronous call?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download