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] ?>
}
Steve Tauber
10.3k5 gold badges45 silver badges48 bronze badges
asked Mar 21, 2013 at 22:38
CaitlinHavener
1,4183 gold badges24 silver badges54 bronze badges
-
2Output 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.user1726343– user17263432013年03月21日 22:41:15 +00:00Commented 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.adeneo– adeneo2013年03月21日 22:41:21 +00:00Commented 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.Okan Kocyigit– Okan Kocyigit2013年03月21日 22:45:42 +00:00Commented Mar 21, 2013 at 22:45
-
1Whatever 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.j08691– j086912013年03月21日 22:47:58 +00:00Commented 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 ?adeneo– adeneo2013年03月21日 22:48:53 +00:00Commented Mar 21, 2013 at 22:48
2 Answers 2
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.
answered Mar 21, 2013 at 22:45
Jonathan Kuhn
15.3k3 gold badges34 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Jonathan Kuhn
@ocanal OP has an array of countries in php and is trying to get that into javascript so they can lookup code in javascript.
Okan Kocyigit
Ok I got it, that should be like this, not in her way.
function getCountry(code)
{
var codes = <?php echo json_encode($codes);?> ;
return (codes[code] || null);
}
answered Mar 21, 2013 at 22:46
darma
4,7571 gold badge27 silver badges26 bronze badges
Comments
default