Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string in Javascript

I am trying to create a simple function that will return the correct string when called:

function getState(abbr){
   if (abbr=="WY")
   {
   return "Wyoming";
   }
}

and then the call is like this:

var stateName = getState("WY");

However all that is getting returned is: 0

Sorry if I am missing something obvious.

UPDATE - my orig prob was because of a "&" here's the real code I'm dealing with:

function getState(abbr){
    var url = "states.asp"
    var state = ""; 
    $.get(url, function(data) {
        var i = 0;
        $.each($('state',data),function(index, el) {            
            if (abbr == ($(this).attr("abbr"))){
                //alert($(this).attr("abbr"));
                state = $(this).text();
            }//if (abbr == $(this).attr("abbr")){
        });//$.each($('state',data),function(index, el) {
    }).success(function() { 
        alert("x" + state);
        return state;
    }); //.success(function() { 
    //$.get(url, function(data) {
    alert("y" + state); 
    return state;
}

I am getting "undefined" as a result to my call:

alert(getState("WY"));

Alert("x" + state) works.

UPDATE #2 --- here is all that states.asp generates (for now)... later it will return companies, etc:

<?xml version="1.0" encoding="utf-8"?>
<STATELIST>
<STATE abbr="AL">Alabama</STATE>
<STATE abbr="AK">Alaska</STATE>
<STATE abbr="AZ">Arizona</STATE>
<STATE abbr="AR">Arkansas</STATE>
<STATE abbr="CA">California</STATE>
<STATE abbr="CO">Colorado</STATE>
<STATE abbr="CT">Connecticut</STATE>
<STATE abbr="DE">Delaware</STATE>
<STATE abbr="FL">Florida</STATE>
<STATE abbr="GA">Georgia</STATE>
<STATE abbr="HI">Hawaii</STATE>
<STATE abbr="ID">Idaho</STATE>
<STATE abbr="IL">Illinois</STATE>
<STATE abbr="IN">Indiana</STATE>
<STATE abbr="IA">Iowa</STATE>
<STATE abbr="KS">Kansas</STATE>
<STATE abbr="KY">Kentucky</STATE>
<STATE abbr="LA">Louisiana</STATE>
<STATE abbr="ME">Maine</STATE>
<STATE abbr="MD">Maryland</STATE>
<STATE abbr="MA">Massachusetts</STATE>
<STATE abbr="MI">Michigan</STATE>
<STATE abbr="MN">Minnesota</STATE>
<STATE abbr="MS">Mississippi</STATE>
<STATE abbr="MO">Missouri</STATE>
<STATE abbr="MT">Montana</STATE>
<STATE abbr="NE">Nebraska</STATE>
<STATE abbr="NV">Nevada</STATE>
<STATE abbr="NH">New Hampshire</STATE>
<STATE abbr="NJ">New Jersey</STATE>
<STATE abbr="NM">New Mexico</STATE>
<STATE abbr="NY">New York</STATE>
<STATE abbr="NC">North Carolina</STATE>
<STATE abbr="ND">North Dakota</STATE>
<STATE abbr="OH">Ohio</STATE>
<STATE abbr="OK">Oklahoma</STATE>
<STATE abbr="OR">Oregon</STATE>
<STATE abbr="PA">Pennsylvania</STATE>
<STATE abbr="RI">Rhode Island</STATE>
<STATE abbr="SC">South Carolina</STATE>
<STATE abbr="SD">South Dakota</STATE>
<STATE abbr="TN">Tennessee</STATE>
<STATE abbr="TX">Texas</STATE>
<STATE abbr="UT">Utah</STATE>
<STATE abbr="VT">Vermont</STATE>
<STATE abbr="VA">Virginia</STATE>
<STATE abbr="WA">Washington</STATE>
<STATE abbr="WV">West Virginia</STATE>
<STATE abbr="WI">Wisconsin</STATE>
<STATE abbr="WY">Wyoming</STATE>
</STATELIST>
like image 909
tree Avatar asked Dec 28 '12 22:12

tree


1 Answers

Easiest approach is to make a hash - no function needed.

var states = {
    'AL': 'Alabama',
    'AK': 'Alaska',
    'AZ': 'Arizona',
    'AR': 'Arkansas',
    'CA': 'California',
    'CO': 'Colorado',
    'CT': 'Connecticut',
    ...
    'WY': 'Wyoming'
};

var stateName = states["WY"];

EDIT

Now I better understand that getState() needs to retrieve State names from the server. This puts you into the world of asynchronous coding, which is quite different from normal, synchronous coding.

The most important thing to realise is that getState() can't simply return a state name for a given state abbreviation. Why? Because the ajax call to the server is asynchronous - in other words getState() won't wait for the server's response before returning.

There are essentially two approaches to handling asynchronicity :

  • pass callback function(s) to getState() to tell it what to do when a response is received
  • arrange for getState() to return a special type of object called a "promise" which can be handled where getState() is called, in such a way that it will respond when the server has responded.

The code below adopts the second approach.

var states = {};//cache of state names, with state abbreviations as keys
function getState(abbr) {
    var dfrd = $.Deferred();//A deferred object, whose promise will be returned.
    if(!states[abbr]) {
        $.ajax({
            url: "states.asp",
            dataType: 'XML',
            success: function(data) {
                //Load up the cache
                $.each($('state', data), function(i, el) {
                    states[el.attr('abbr')] = $(el).text();
                });
                //Now resolve or reject the deferred object depending in whether states[abbr] has been cached
                if(states[abbr]) {
                    dfrd.resolve(abbr, states[abbr]);//Success! Let's resolve the deferred object (and its promise).
                }
                else {
                    dfrd.reject(abbr, 'States successfully downloaded but ' + abbr + ' was not included');
                }
            },
            error: function() {
                dfrd.reject(abbr, 'Download of states failed');
            }
        });
    }
    else {
        //The state name is already cached
        //The deferred object (and its promise) can be resolved without needing to make another ajax call.
        dfrd.resolve(abbr, states[abbr]);
    }
    return dfrd.promise();
}

untested

Now all you need to know is how to call getState().

getState("WY").done(function(abbr, state) {
    alert(abbr + ': ' + state);
    //other stuff here
}).fail(function(abbr, message) {
    alert(abbr + ': ' + message);
    //other stuff here
});

As you can see, the value that you wanted getState() to return now appears as the second argument of a .done() function. For good measure, the abbreviation ("WY") appears as the first argument.

If you want to handle error conditions (always a good idea), then do so in a .fail() callback.

See comments in code for more clues as to how everything works.

like image 139
Beetroot-Beetroot Avatar answered Oct 03 '22 14:10

Beetroot-Beetroot