Back to blog

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 AngularJS 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 DEMO.

The Form (searchform.htm)

<!DOCTYPE html>
<html ng-app>
<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>


	<div ng-controller="SearchCtrl">
	<form class="well form-search">
		<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>		
<pre ng-model="result">


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()")
	$ = function() {
		// Create the http post request
		// the data holds the keywords
		// The request is a JSON request.
		$$scope.url, { "data" : $scope.keywords}).
		success(function(data, status) {
			$scope.status = status;
			$ = data;
			$scope.result = data; // Show result from server in our <pre></pre> element
		error(function(data, status) {
			$ = data || "Request failed";
			$scope.status = status;			

The server-side script (search.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
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!

Labels: angularjs javascript php

75 Responses

  1. tom on June 20, 2012

    Wow, I have been looking for such a simple proof of concept. All of examples I have seen have either been json files or some obscure webservice with what knows backend. Thanks for such a simple and complete proof of concept!!!!!!

    • Peter Prins on June 20, 2012

      Hi Tom,

      Thanks for your kind comment. I am always charmed by proof of concept examples myself so I thought lets give it a try.
      These simple examples get you started exactly how you want.

      Although the AngularJS examples might seem very simple from the point of view of their developer ;-)

    • For some reason the above script doesn’t work for me. Not sure what could be the issue.

  2. David on June 24, 2012

    Awesome! Thanks! Been struggling with this for a while. You should consider submitting it to the AngularJS docs because many people have been having similar issues with $

    It’s weird though that PHP doesn’t include the JSON posted data in the $_POST variable. Some site i’ve found says it does this in the $_POST[‘json’] variable, but it so doesn’t!

    • Peter Prins on May 25, 2012

      Hi David,

      I will post it at the AngularJS docs. JSON is a specific internet media type. Of course you can put a JSON string in a HTTP Post request, but this doesn’t make it a JSON request.

      I’m glad I could help you with AngularJS.

  3. i try to decide between angularjs and knockout…+1 after your post for angularjs.

  4. absolutely awesome… I have been looking for this ages!

    Thanks soooo much!

  5. Vagner on November 12, 2012

    Muito obrigado, seu conteúdo foi de grande ajuda.


    Thank you, your content has been of great help.

  6. Cool. Big thx.

  7. Great example. Thanks.

    • shirish on December 7, 2012

      Its great of u,thanks……..was facing d same problem

  8. Perhaps this is overdesign but I wonder if you shouldn’t be using a service instead of a controller to actually do the HTTP stuff. The AngularJS reasoning is that services are injected at runtime so, during testing, you would inject a dummy search service which returned test results instead of actually doing the HTTP. Also, you could later easily refactor by swapping out the implementation of your search service without changing your controller. I realise this misses the point of your demo :-)

    • Peter Prins on December 3, 2012

      Hi Marc,

      Thanks for your feedback!
      You’re absolutely right about the services implementation and how you could easily switch between staging and production environments or
      other services by injection.

      Although for this demo or ‘proof of concept’ it’s a bit overkill. I just wanted to show people how to connect to a PHP back-end, and obviously people like it. They could use it in their services :) They should however, use the AngualarJS guidelines and concepts while creating larger applications with it.

  9. stirling on December 13, 2012

    I could just hug you right meow!

  10. Great post Peter ! it saved me from bad dreams tonight, after stumbling through all the webservices tutorials the whole day. Biggest problem was i could only find it when I typed php+mysql+json+angularjs in google :)

    • Peter Prins on January 23, 2013

      Thanks Vipin, I’ve added the json and mysql tag. Hopefully Google will pick it up and combine the tags :-)

  11. Campa Franz on January 26, 2013

    nice simple example. But it is not working for me in IE8, is it normal?
    server: Apache/2.0.52 (Fedora)
    client and error mesaage:
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BTRS122288; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
    Sat, 26 Jan 2013 09:40:31 UTC

    ErrorMessage: Operaci nelze dokonit kvoli chyb c00ce56e.
    Line: 95
    Char: 498
    Code: 0

  12. Campa Franz on January 26, 2013

    It is not normal ;-)
    Demo on works well.
    Old apache web server or its configuration is probably responding.

  13. how to get multiple array

  14. Sam Elowitch on April 23, 2013

    I don’t get it — where is the data being search come from? I don’t see a connection script to a database, so is it all stored locally?

    • Peter Prins on April 23, 2013

      Hi Sam,

      In this demo I use a dummy record set (the array). Ofcourse you need a query and a connection to the database.

      This tutorial is mainly about AngularJS with a PHP backend.

      You could do something like this with my example:

      $q = 'SELECT * FROM table WHERE title LIKE "%'.$objData->data.'%";
      $res = mysqli_query($res);

      $objResult = mysqli_fetch_object($res);
      echo $objResult->title;

      But this is beyond the scope of the tutorial.

  15. Anon Im on May 17, 2013

    How do I get the search.php to get its data from a separate .json file which has in it the following:

    item id
    item name
    item category

    And display that data if I search by any of the id, name or category, even if incomplete search query?

  16. Harish Oraon on May 25, 2013

    nice to see the working architecture.I am still confused though with the available frameworks , what can the most appropriate for communicating with the back end..

  17. Hi All

    my template url: test.php

    how i get BlogId value in php file.

  18. Sarfraz Ahmad on October 19, 2013

    Wow ……. i was looking for such a nice and simple example ….. Thanx a lot

  19. How do i connect PHP with yeoman angular projects?

  20. sharon on November 8, 2013

    Hello and thanks for the tutorial!
    i have a problem: when the server PHP file is POSTed to, i am getting a 404.
    what am i missing? i have scanned Google and didn’t find an answer….

  21. Hi! thanks for the tutorial, but can you please add a php connection to mysql and get them over the query please?

  22. aj07mm on March 21, 2014

    i’m wondering what is this path php://input
    $data = file_get_contents(“php://input”);

    • Peter Prins on March 24, 2014

      This is a PHP input stream. php://input is a read-only stream that allows you to read raw data from the request body.
      In our case the JSON input has an application/json type and can’t be read by normal $_POST variables. Read more here:

  23. Hi. I try, but my test result in data is equal to my php content, not the result. I run my php on the server and it function well, it returns what I want, but over AngularJS, it does not work. Can you help me please?

    • Peter Prins on March 30, 2014

      Are you sure you use the correct URL in the AngularJS part? It seems that your server doesn’t know it’s a PHP file. Maybe you forgot to add .php in the $scope.url part?

  24. Mark Wilson on April 19, 2014

    I must be missing something. In search.php, I am trying to search a MYSQL database for the target string, using an edited version of the suggested code above:
    //SELECT * from wine WHERE name like “%CHAT%”
    $q = ‘SELECT * FROM wine WHERE name LIKE “%’.$objData->data.’%”‘;
    $res = mysqli_query($q);

    $objResult = mysqli_fetch_object($res);
    echo $objResult->name . ” name is always empty.
    Is there a problem you see with my code?
    Is there a way to prove that search.php is accessing the database at all?
    Sorry for the elementary questions, I’ve been doing PHP/MySQL for a while, but have never tried to access MySQL using Angular.

    • Peter Prins on April 19, 2014

      Hi Mark,

      I assume the connection is already made in your script :)
      What do you see when you:

      a) echo $q; //Should be the full sql query
      b) var_dump($objResult); // should be a result object

  25. on April 22, 2014

    Thanks for sharing, helped my project

  26. Mark Wilson on April 24, 2014

    Peter Prins on April 19, 2014
    Hi Mark,

    I assume the connection is already made in your script :)
    What do you see when you:

    a) echo $q; //Should be the full sql query
    b) var_dump($objResult); // should be a result object
    Yeah, in my index.php that’s the first thing included.
    include “includes.php”;
    $data = file_get_contents(“php://input”);
    $objData = json_decode($data);
    $target = $objData->data;
    // perform query or whatever you wish, sample
    $q = ‘SELECT * FROM wine WHERE name LIKE “%’.$objData->data.’%”‘;
    echo “QUERY=” . $q . “\n”;
    $res = mysqli_query($q);

    $objResult = mysqli_fetch_object($res);
    echo “objResult=”;
    echo “\n”;
    echo “name=” . $objResult->name . ” <- result for query=$q";
    $allwines = GetAllWines();
    echo "\nCount of AllWines=:" . count($allwines) . "\n";
    QUERY=SELECT * FROM wine WHERE name LIKE "%charteau%"

    name= <- result for query=SELECT * FROM wine WHERE name LIKE "%charteau%"
    Count of AllWines=:12
    The last line is from one of my own generic query routines, so that seems to work.
    But not the "simpler" mysql query earlier. What am I missing?

    • Peter Prins on April 27, 2014

      Hi Mark,

      I can’t tell what is going wrong, it’s a bit hard without seeing the actual code. Fortunately the data from the Ajax call works which is in the scope of this article.
      What happens when you echo the resulting query and paste that in for example phpMyadmin? Try to see if there is anything in your webserver’s error.log file

    • greatAlex on September 18, 2014

      Hi Mark

      I doubt any wine has “charteau” in its name – get rid of the “r” in the middle and let us know :-)


  27. Jitendra on April 25, 2014

    absolutely awesome… I have been looking for this ages!

  28. ribe on April 29, 2014

    Just posted a question how to extend this example – how to add timeout?

    If the call is connected to the input field on-cnahge:

    it will be logical to add some time delay before making the AJAX call.

  29. Tom on May 2, 2014

    Clear explained very useful … Leaves me with one beginners question .

    Can this be put in one file … form, Search.js and Search.php = Search_form.php or are 3 files mandatory in this case ?

  30. Wissam on May 6, 2014

    So I followed your example but I keep getting this error… It’s a silly one too.
    In my .js file.
    Error: success is not defined

  31. kangys on May 11, 2014

    function SearchCtrl($scope, $http){
    //검색할 url
    $scope.url = “search.php”;
    $ = function(){
    $$scope.url, {“data”:$scope.keywords}).
    $scope.status = status;
    $ = data;
    $scope.result= data;
    $ = data || “Request failed”;
    $scope.status = status;


  32. kangys on May 11, 2014

    sorry wrong writing

  33. Ravindra on May 26, 2014


    I am using angularjs with requirejs, in $http post when I mention the php file path which is in different directory it doesn’t locate the php file and getting file not found error, this happens even if i copy the php file within the same directory as the html file placed.

    Any suggestion is much helpful.


  34. jermaine on June 13, 2014

    great tutorial

  35. Vijai on June 13, 2014

    Nice tutorial for beginners..

  36. akhilesh on June 30, 2014

    my team feels implementing the above code with “file_get_contents(“php://input”) ” i not safer, so i was requested to use post method, so how can this code be modified so that i could receive the data via php-post method. your work is really working great, nice work

    • Peter Prins on July 1, 2014

      You can’t get it by PHP post as it’s not form data but JSON data (application/json). It is safe to use file_get_contents(‘php://input’); as it is just a php input stream which is always available. It might be even safer :)

  37. Sabrina on June 30, 2014

    There is a typo on this page.
    >>>Recently I found AngularJS, a so called “Superheroic Javascript MVC framework” by Goole®.

    The last word should be Google. You may fix it soon or just ignore that, I know I’m toooo picky. XDDDD

    BTW, this is a very nice article for beginners.

    • Peter Prins on July 1, 2014

      Hi Sabrina, Thanks I’ve updated it :-)

  38. rajmohan s on July 2, 2014

    great tutorial. you have mentioned $data = file_get_contents(“php://input”); to get the data. can you explain more about this since aim not unaware of this method. Thanks

  39. Daniel on July 23, 2014

    I’m not sure I understand. Why is it we need the search.js. If I remove this file the example still works.

    • Peter Prins on July 24, 2014

      That’s not possible, probably some browser cache. Try to hit CTRL+F5 for a hard refresh.

  40. Richard Levy on August 8, 2014

    WOW! This has been the clearest information I have found. I have been looking at REST and other solutions. I like simple (at least to start)


  41. Ismael on September 9, 2014

    Muito obrigado, salvou meu dia!

  42. you are great !!!
    i found what i searched for, thanks a milion !


  43. Great example. I have used it and it works like a charm. I have a basic question. How is the php file being executed? For example, on a command line we can execute a file as> php file.php. In the URL I just see the path of the php file. It isn’t really a command. If I have to use a perl file instead of php how will that be executed?

  44. 私がだった後何丁度。 認められる多くおよびあなたは学校のために余りに涼しい。
    [translation: Exactly what I was after. Much appreciated and you are too cool for school!]

  45. Fernando on September 29, 2014

    my modified version of search.js:


    var app = angular.module(“myapp”,[ ]);

    app.controller(‘SearchCtrl’,[‘$scope’, ‘$http’ ,function($scope, $http){

    //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()”)
    $ = function() {

    // Create the http post request
    // the data holds the keywords
    // The request is a JSON request.
    $$scope.url, { “data” : $scope.keywords}).
    success(function(data, status) {
    $scope.status = status;
    $ = data;
    $scope.result = data; // Show result from server in our element
    error(function(data, status) {
    $ = data || “Request failed”;
    $scope.status = status;


  46. mahmoud on October 9, 2014

    This tutorial is just great it made my day. Hence could this be used in a bigger project?

  47. […] Another more accomplished use of this method – a simple search with AngularJS and PHP […]

  48. Thank You on January 20, 2015

    Thank-you for such a cogent, simple example! Very nice job and much appreciated!

  49. Vijay Thummar on April 21, 2015

    Really Awesome, Simple and self explained !!!!

    Vijay Thummar

  50. […] found a tutorial here about using the $http service to send data to […]

  51. benjamin on July 26, 2016

    wow, the tutorial is great. i was thinking if there is a way of making the search live

  52. Curious Questioner on October 28, 2016

    Great Explanation! :) Keep posting such articles.

    Although I have a doubt, can you please explain what happens when I have to pass multiple parameters to my controller from PHP server. I am confused, how to go about it.
    I have to pass three arrays, but when I pass the below:
    $json_string = array($json_string_leg, $json_string_bill, $json_string_committee);
    echo $json_string;

    I am unable to retrieve the value. Please help!!

Drop a note