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 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 this 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 monitor the select through JS. When the select changes, use jQuery's get method to obtain 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 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); ?>
Readers who are interested in more Yii-related content can check out the special topics on this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent PHP Development Framework", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.