jwi jwi - 5 months ago 21
Javascript Question

Array push inside getJSON

I use the following function as onclick event on an ahref link:

function checkOrgSaved() {
var orgName = $.trim($("#orgName").val());
var orgNames = new Array();

$.getJSON("organizations?action=getOrganizations&onlyName=true&CSRFToken=" + csrf_token, function (result) {
for (var i = 0; i < Object.keys(result.Orgs).length; i++) {
var org = result.Orgs[i].name;
orgNames.push(org);
}
});

if ($.inArray(orgName, orgNames) == -1 || orgName == 0){
alert("Foobar.");
$("#editLink").attr("href", "javascript:void(0);");
}
}


Like this, the
orgNames
array in the
if
statement is always empty. Why?

However if I declare the
orgNames
array inside the
getJSON
call and put the
if
statement also inside the
getJSON()
call, the array is filled correctly, but the line
$("#editLink").attr("href", "javascript:void(0);");
does not work and a redirect is performed with a click on the ahref element.

What I'm trying to achieve is: If the orgName is empty or NOT in the orgNames array an JS alert should be thrown - without an redirect on the other page.

Answer

This is because the $.getJSON call is asynchronous, meaning the if statement will be executed before the JSON data is received and the callback is executed and orgNames is populated.

You might want to fetch the JSON and populate the array before the click occurs, and then just check agains the values:

var orgNames = new Array();

$.getJSON("organizations?action=getOrganizations&onlyName=true&CSRFToken=" + csrf_token,   function (result) {
  for (var i = 0; i < Object.keys(result.Orgs).length; i++) {
    var org = result.Orgs[i].name;
    orgNames.push(org);
  }
});

function checkOrgSaved() {
  var orgName = $.trim($("#orgName").val());

  if ($.inArray(orgName, orgNames) == -1 || orgName == 0){
    alert("Foobar.");
    $("#editLink").attr("href", "javascript:void(0);");
  }
}

This would also help avoid additional requests for the same JSON data.