The example in this article describes how Yii2 automatically obtains form data based on Ajax. Share it with everyone for your reference. The details are as follows:
There are two tables here. The table structure is as follows. The locations table stores information such as provinces and postal codes. The model and curd of the two tables are both generated using GII.
yii2advanced.customers table
customer_id:int(11)
customer_name:varchar(100)
zip_code:varchar(20)
city:varchar(100)
province:varchar(100)
yii2advanced.locations table
location_id:int(11)
zip_code:varchar(20)
city:varchar(100)
province:varchar(100)
Here we need to automatically fill in the city and province information corresponding to the zip code in the form after the customer selects zip_code
Implementation method
First You need to add a method in the Locations controller. He can get the corresponding location information by getting the zip_id
public function actionGetCityProvince($zipId) { $location = Locations::findOne($zipId); echo Json::encode($location); }
Then listen to the select through JS. When the select changes, use jQuery's get method to get the corresponding information. And use jQuery's attr method to set the value of city and province
JS code, located in the customer's form view
#zipCode is the id of the select
<?php $script = <<<JS jQuery('#zipCode').change(function(){ var zipId = $(this).val(); jQuery.get('index.php?r=locations/get-city-province',{zipId:zipId},function(data){ var data = jQuery.parseJSON(data); jQuery("#customers-city").attr("value",data.city); jQuery("#customers-province").attr("value",data.province); }); }); JS; $this->registerJs($script); ?>
I hope this article will help everyone use PHP based on the Yii framework Programming helps.
For more articles related to Yii2’s method of automatically obtaining form data based on Ajax, please pay attention to the PHP Chinese website!