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>
<head>
<title>Search form with AngualrJS</title>
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
	<script src="http://code.angularjs.org/angular-1.0.0.min.js"></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!

Labels: angularjs javascript php

57 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 $http.post().

    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.

    English:

    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

    Hi
    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
    URI: http://code.angularjs.org/angular-1.0.0.min.js

  12. Campa Franz on January 26, 2013

    It is not normal ;-)
    Demo on http://www.cleverweb.nl/angularjs/searchform.htm 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

    $routeProvider.when(/blog/:BlogId)
    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….
    thanks!

  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

    hi,
    i’m wondering what is this path php://input
    in
    $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: http://www.php.net/manual/en/wrappers.php.php

  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:
    [code]
    // THIS SQL WORKS IN THE ACTUAL DATABASE:
    //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. journeycoder.com 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.
    Code:
    *************
    include “includes.php”;
    $data = file_get_contents(“php://input”);
    $objData = json_decode($data);
    $target = $objData->data;
    // perform query or whatever you wish, sample
    // THIS SQL WORKS IN THE ACTUAL DATABASE: SELECT * from wine WHERE name like “%CHAT%”
    $q = ‘SELECT * FROM wine WHERE name LIKE “%’.$objData->data.’%”‘;
    echo “QUERY=” . $q . “\n”;
    $res = mysqli_query($q);

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

    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

  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?
    http://stackoverflow.com/questions/23360334/angularjs-timeout-ajax-call

    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”;
    $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;
    });

    }
    }

  32. kangys on May 11, 2014

    sorry wrong writing

  33. Ravindra on May 26, 2014

    Hi,

    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.

    Thanks.

  34. jermaine on June 13, 2014

    great tutorial

  35. Vijai on June 13, 2014

    Nice tutorial for beginners..

  36. akhilesh on June 30, 2014

    hi,
    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

    Hi,
    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

Drop a note