http://www.keyboardninja.eu/webdevelopment/a-simple-search-with-angularjs-and-php
Recently I found AngularJS, a so called “Superheroic Javascript MVC framework” by Google?.
I must say I am impressed by its simple, readable and quick way of working.
This framework is smart, very smart. Go have a look when you’re ready on the site. Especially the basics tutorial is worth watching for beginners.
I have created a simple search form with a PHP back end and AngularJS to handle the request and response.
It’s divided in three elements:
-
The form
-
The AngularJS script
-
The server-side script
You can copy paste the source code from below or have a look at this .
The Form (searchform.htm)
-
<!DOCTYPE html>
-
<html ng-app>
-
<head>
-
<title>Search form with AngualrJS</title>
-
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
-
<script src=""></script>
-
<script src="search.js"></script>
-
</head>
-
-
<body>
-
-
<div ng-controller="SearchCtrl">
-
<form class="well form-search">
-
<label>Search:</label>
-
<input type="text" ng-model="keywords" class="input-medium search-query" placeholder="Keywords...">
-
<button type="submit" class="btn" ng-click="search()">Search</button>
-
<p class="help-block">Try for example: "php" or "angularjs" or "asdfg"</p>
-
</form>
-
<pre ng-model="result">
-
{{result}}
-
</pre>
-
</div>
-
</body>
-
-
</html>
The AngularJS script (search.js)
-
function SearchCtrl($scope, $http) {
-
$scope.url = 'search.php'; // The url of our search
-
-
// The function that will be executed on button click (ng-click="search()")
-
$scope.search = function() {
-
-
// Create the http post request
-
// the data holds the keywords
-
// The request is a JSON request.
-
$http.post($scope.url, { "data" : $scope.keywords}).
-
success(function(data, status) {
-
$scope.status = status;
-
$scope.data = data;
-
$scope.result = data; // Show result from server in our <pre></pre> element
-
})
-
.
-
error(function(data, status) {
-
$scope.data = data || "Request failed";
-
$scope.status = status;
-
});
-
};
-
}
The server-side script (search.php)
-
<?php
-
// The request is a JSON request.
-
// We must read the input.
-
// $_POST or $_GET will not work!
-
-
$data = file_get_contents("php://input");
-
-
$objData = json_decode($data);
-
-
// perform query or whatever you wish, sample:
-
-
/*
-
$query = 'SELECT * FROM
-
tbl_content
-
WHERE
-
title="'. $objData->data .'"';
-
*/
-
-
// Static array for this demo
-
$values = array('php', 'web', 'angularjs', 'js');
-
-
// Check if the keywords are in our array
-
if(in_array($objData->data, $values)) {
-
echo 'I have found what you\'re looking for!';
-
}
-
else {
-
echo 'Sorry, no match!
That should do it!
Posted: April, 2014 in Webdevelopment
阅读(1139) | 评论(0) | 转发(0) |