AngularJS Search Test
Uses AngularJS and XHR to submit a search form.
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div data-ng-app="search-test">
<div ng-controller="SearchCtrl">
<form class="well form-search">
<label>Search:</label>
<input type="text" data-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>
<p data-ng-show="loading">Loading...</p>
<pre data-ng-hide="loading" data-ng-model="result">
{{result}}
</pre>
</div>
</div>
JavaScript
var app = angular.module('search-test', [], function($httpProvider)
{
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data)
{
return angular.isObject(data) && String(data) !== '[object File]' ? $.param(data) : data;
}];
});
function SearchCtrl($scope, $http) {
$scope.url = '/echo/json/'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {
$scope.loading = true;
var jsonData = angular.toJson({ "data" : $scope.keywords});
var requestData = { "json" : jsonData, "delay" : 2 };
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
$http.post($scope.url, requestData ) .
success(function(data, status) {
$scope.response = data;
$scope.loading = false;
$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;
});
/* PHP */
/* header('Content-Type: application/json');
echo json_encode($_POST); */
};
}