0

I need to convert country codes into their name from Javascript. I found a php array of country codes but I need to pass a javascript variable into the php array to get the country code. Any way to do something like the following? This errors out of course.

function getCountry(code)
        {
            <?php echo $code=?> code;
            return <?php echo $countries[$code] ?>
        }
8
  • 2
    Output the data structure containing your country codes as JSON, then store it in a variable in JS (the JSON format is native to JS). You can then retrieve values from it as you please. Commented Mar 21, 2013 at 22:41
  • Why not just convert that array to a valid javascript object, and use the countrycodes as keys to get the names. Commented Mar 21, 2013 at 22:41
  • you can't pass value from javascript to php. it's impossible like this way. you should create an api. Commented Mar 21, 2013 at 22:45
  • 1
    Whatever you nitwits do, make sure you give a great answer. user1964129 might be the hottest chick on SO and the last thing we need to do is frighten her off. Commented Mar 21, 2013 at 22:47
  • 1
    @j08691 - +1, I guess I was'nt the only one that noticed that, I just found it a bit inappropriate to comment on it ? Commented Mar 21, 2013 at 22:48

2 Answers 2

5

in javascript:

function getCountry(code){
    var countries=<?=json_encode($countries)?>;
    return countries.hasOwnProperty(code)?countries[code]:null;
}

I modified it to use a ternary for the error checking, just shorter code.

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

2 Comments

@ocanal OP has an array of countries in php and is trying to get that into javascript so they can lookup code in javascript.
Ok I got it, that should be like this, not in her way.
1
function getCountry(code)
        {
            var codes = <?php echo json_encode($codes);?> ;
            return (codes[code] || null);
        }

Comments

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.