Getting values ​​from a PHP associative array using jQuery

I have an html select element generated in PHP from an array as follows

$countries = array( array('iso' => 'AF', 'name' => 'Afghanistan', 'key' => 'Red'), array('iso' => 'AX', 'name' => 'Γ…land Islands','key' => 'Yellow'), array('iso' => 'AL', 'name' => 'Albania', 'key' => 'Blue') ); $select = '<select id="country_select" onchange="countryfind()">'; foreach($countries as $country) { $select .= '<option value="'.$country['key'].'">'.$country['name'].'</option>'; } $select = '</select>'; return $select; 

The javascript function is used in the selection field to display the country key of the selected country:

 function countryfind(){ jQuery('#countrykey').text( jQuery('#country_select option:selected').val() )}; 

I want to use this key to interact with another PHP array that contains country information and displays that country in div # countrykey instead of the selected value:

 $si_federations = array( 'Red' => array('name'=>'A Red Country', 'url'=>'http://www.redcountry.com'), 'Blue' => array('name'=>'A Blue Country', 'url'=>'http://www.soroptimisteurope.org'), ); 

Is this something that can be easily achieved, or is my approach completely wrong?

+5
source share
2 answers

You are on the right track. So, here's how to do it, what you want

In your <script> block, we want to output this array to JSON

 var federations = <?php echo json_encode($si_federations); ?>; 

Now, when you run countryfind , we want to pull the value from this object and display it. So change your function

 function countryfind(){ var fed; var selected = jQuery('#country_select option:selected').val(); if(federations[selected] !== undefined) fed = federations[selected]; else fed = {"name":"Default Name", "url":""}; //placeholders if it not defined jQuery('#countrykey').text( selected + ' - ' + fed.name + ' ' + fed.url; )}; 

I don’t know how you want it to be displayed (I just dropped it as text for simplicity), but it will give you the data you need so you can get it from there

+4
source

You need to convert your associative php array to a js object for further reference. Since php runs on the server and you perform each action on the client side, so immediately after loading the page, your php is useless. You need js var so that you can reference it further. Like this:

 <script> var countries = []; var country = {}; <?php foreach($si_federations as $k => $country): ?> <?php foreach($country as $key=>$val): ?> country['<?php echo $key; ?>'] = '<?php echo $val; ?>'; <?php endforeach; ?> countries['<?php echo $k; ?>'] = country; <?php endforeach; ?> function countryfind(){ var keyVal = jQuery('#country_select option:selected').val(); jQuery('#countrykey').text('name: '+countries[keyVal]['name']+' url: '+countries[keyVal]['url']); } </script> 

I hope this helps

+1
source

Source: https://habr.com/ru/post/1260138/


All Articles