AngularJS is very intersting and smart javascript framework. In this post explain you how to create Search Form using AngularJS in PHP.
Steps to Create Search Form Using AngularJS and PHP:
1) First create a simple html form with the name of “index_form.html”. Must include angular.min.js external libraries and angularJS script file. Use below form code for it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<html> <head> <title>How to Create Search Form Using AngularJS and PHP</title> <script src="search.js"></script> <script src="http://code.angularjs.org/angular-1.0.0.min.js"></script> </head> <body> <form> <label>Search Box:</label> <input type="text" ng-model="keywords" placeholder="search keyword"> <button type="submit" ng-click="search()">Search</button> // use below dummy array value for search </form> <pre ng-model="result"> {{result}} </pre> </body> </html> </html> |
2) Now create AngularJs script file with name of “search.js”. We already include this script file in above HTML form code.
In this script file write a function which will call on form button click. Check below script code:
[sociallocker id=”1175″]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<script type="text/javascript"> function SearchCtrl($scope, $http) { $scope.url = 'searchresult.php'; // search url $scope.search = function() { $http.post($scope.url, { "data" : $scope.keywords}). success(function(data, status) { $scope.status = status; $scope.data = data; $scope.result = data; }) . error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; } </script> |
[/sociallocker]
3) Now write server side script code for final step. This “searchresult.php” file handle the json request and match the search keyword. We take it static array for matching the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $data = file_get_contents("php://input"); // GET and POST not working to read this data $query_data = json_decode($data); // create dummy array $keyword_values = array('red', 'yellow', 'green', 'blue' ); // Check if the keywords are in our array if(in_array($query_data->data, $keyword_values)) { echo 'Keyword match'; } else { echo 'Not Matched'; } ?> |
Quite simple and easy to implement this angularJS search form. You need to place all three files in same directory to execute this. If you find this post useful, please share with others. Thanks