Angular js with php

Ajax with AngularJS and PHP

Ajax is a technology that enables us to update parts of a webpage, without the need to reload the page. Ajax improves the user experience because it reduces the time it takes to update the content of a page, and the webpage is updated without a blink, so overall the webpage behaves more like a native application. A major example for AJAX can be found in Google Maps where we navigate from one map to another without reloading the page.

Ajax works by sending requests for data from the browser to the server, and the server that returns the requested data back to the browser. When a user performs actions like clicking a button or scrolling down the page, JavaScript code which listens to the event, sends a request to the server side, and the server process the request, and creates a response which is then sent back to the browser so it can be used to update the content of the page.

In AngularJS, we use the $http service that makes working with AJAX very simple. In this tutorial, we are going to develop a phone book application that can store people’s names and phone numbers. The application enables us to add, read and delete the records. The server side is written in PHP.

The source code for the tutorial can be downloaded from the link in the conclusion section.

AJAX with AngularJS and PHP

Push the button to see
the code in action.

The Angular $http service

The $http service is what we use in Angular applications to perform Ajax calls. In order to use the service we first need to inject it as a dependency to the controller.

  

The $http service has the following parts:

  • The method parameter defines if we get the data by GET or send the data by POST.
  • The url parameter defines the path to the server side (the PHP script).
  • Code to execute in case of success.
  • Code to run in case of failure.
$http(< method: 'GET', url: 'api/get.php' >).then(function (response) < // code to execute in case of success >, function (response) < // code to execute in case of error >);

We need to fetch data from the server so we use the GET method, the PHP script is ‘api/get.php’ . The first callback (then) runs in case of success, and the second in case the server side fails to respond.

Now that we understand the basic syntax for doing AJAX in AngularJS apps, let’s write the HTML for the app.

Читайте также:  By classname selenium python

The HTML

The html part of the application has two parts.

  1. The first part is the form in which the user can fill new names and phone numbers.
  2. The second part contains a list of all the names and phone numbers.

Each of the list items can be deleted by pressing the ‘delete’ button.

We define the application by using ng-app on the html tag. The name of the application is ‘ajaxExample’ .

We define the controller on the div that wraps the form and the list with ng-controller = ‘mainController’

The input fields are defined with ng-model :

We put ng-click=»addPerson()» on the button, so clicking the button submits the new person data.

The list displays the names of all the records with ng-repeat .

Every list item contains a person’s name and phone number and a button for deleting the person with the ‘deletePerson’ function.

The Angular code

We write the AngularJS code in the file ‘assets/js/app.js’ .

The Angular code has 3 functions:

  1. getPeople() does an Ajax call to a PHP script that reads all the records from the database.
  2. addPerson() gets the data which was posted from the form and sends it with Ajax to a PHP script that inserts the new record to the database.
  3. deletePerson() gets the id of a record, and sends an Ajax call to a PHP script to delete the record from the database.
var ajaxExample = angular.module('ajaxExample', []); ajaxExample.controller('mainController',function($scope,$http)< $scope.people; $scope.getPeople = function() < $http(< method: 'GET', url: '/api/get.php' >).then(function (response) < // on success $scope.people = response.data; >, function (response) < // on error console.log(response.data,response.status); >); >; $scope.addPerson = function() < $http(< method: 'POST', url: '/api/post.php', data: >).then(function (response) // on success $scope.getPeople(); >, function (response) < console.log(response.data,response.status); >); >; $scope.deletePerson = function( id ) < $http(< method: 'POST', url: '/api/delete.php', data: < recordId : id >>).then(function (response) < $scope.getPeople(); >, function (response) < console.log(response.data,response.status); >); >; $scope.getPeople(); >);

The database

We store the data that we gather with the form in a people table.

That’s the SQL code for the table:

The PHP

The PHP server side will be in the ‘api/’ folder, and it has the following 4 scripts:

  1. api/connect.php to connect with the database.
  2. api/get.php that reads the data from the database.
  3. api/post.php that is used to add a record to the database.
  4. api/delete.php is used to delete a record from the database.

connect.php

// db credentials define('DB_HOST', 'localhost'); define('DB_USER','root'); define('DB_PASS',''); define('DB_NAME','angular'); // Connect with the database. function connect() < $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME); if (mysqli_connect_errno($connect)) < die("Failed to connect:" . mysqli_connect_error()); > mysqli_set_charset($connect, "utf8"); return $connect; >

get.php to read from the database

 require 'connect.php'; $connect = connect(); // Get the data $people = array(); $sql = "SELECT id, name, phone FROM people"; if($result = mysqli_query($connect,$sql)) < $count = mysqli_num_rows($result); $cr = 0; while($row = mysqli_fetch_assoc($result)) < $people[$cr]['id'] = $row['id']; $people[$cr]['name'] = $row['name']; $people[$cr]['phone'] = $row['phone']; $cr++; > > $json = json_encode($people); echo $json; exit;

post.php to insert new records to the database

We get the data that is posted from the form with the following code:

file_get_contents(The data needs to be json decoded. As you can see in the following code:
 require 'connect.php'; $connect = connect(); // Add the new data to the database. $postdata = file_get_contents("php://input"); if(isset($postdata) && !empty($postdata)) < $request = json_decode($postdata); $newName = preg_replace('/[^a-zA-Z ]/','',$request->newName); $newPhone = preg_replace('/[^0-9 ]/','',$request->newPhone); if($newName == '' || $newPhone == '') return; $sql = "INSERT INTO `people`(`name`, `phone`) VALUES ('$newName','$newPhone')"; mysqli_query($connect,$sql); > exit;

delete.php

Deletes a record from the database.

'connect.php'; $connect = connect(); // Delete record by id. $postdata = file_get_contents("php://input"); if(isset($postdata) && !empty($postdata)) < $request = json_decode($postdata); $id = (int)$request->recordId; $sql = "DELETE FROM `people` WHERE `id` = '$id' LIMIT 1"; mysqli_query($connect,$sql); >

Conclusion

This concludes our experimenting with AngularJS and PHP. Hope it helps. If you have any comments you may leave them in the comments box below.

Joseph Benharosh web developer

Joseph Benharosh is a full stack web developer and the author of the eBook The essentials of object oriented PHP.

Was this tutorial helpful?

If so, the eBook «The essentials of object oriented PHP» can further help you.

eBook object oriented PHP

«The essentials. » is an in-depth guide to help you quickly and easily increase your productivity and become a hot commodity in the job market.

Don’t waste time!
Click on the green button to buy the eBook and start achieving your potential today!

Источник

Запуск и отладка Angular + PHP

Рассмотрим как правильно настраивать Angular для работы с PHP сервером. При получении запроса от Angular, PHP сервер будет формировать запросы к базе данных MySQL и на основе их формировать ответы для Angular.

Установка средств запуска

Linux

Для того, чтобы работать с php в linux надо установить apache2, mysql. Также следует установить phpmyadmin для того, чтобы можно было удобно редактировать базу данных. При установке phpmyadmin автоматически установится и php.

Windows и MacOS

В других операционных средах всё проще немного, можно установить готовые комплекты, например бесплатную версию MAMP.

Настройка htaccess

Если на Angular сайте используется маршрутизация, то в случае, когда пользователь зайдёт на главную страницу сайта, и потом будет переходить на другие страницы – всё будет работать. Но в том случае, когда он зайдёт на сайт по какой-либо странице, отличной от главной, то, чтобы всё корректно работало, следует в PHP настроить .htaccess.

Теперь о .htaccess. При базовой настройке в linux они не поддерживаются обычно. Проверить можно следующим образом: в папку apache, где находится index.html добавляем файл .htaccess со случайным текстом. Так как его не возможно разобрать, то должна быть выведена ошибка «500 Internal Server Error» при попытке открытия в браузере localhost. Если этого не происходит, то следует выполнить следующие правки: добавить разрешение обрабатывать .htaccess. Это можно сделать, подкорректировав /etc/apache2/apache2.conf, изменив «AllowOverride None» на «AllowOverride All» для нужной директории. Вот пример:

 Options Indexes FollowSymLinks AllowOverride All Require all granted 

Чтобы применить изменения, следует выполнить его перезагрузку с помощью команды:

sudo systemctl restart apache2

После этого /var/www/html/.htaccess должен обрабатываться.

Но не факт что будут обрабатываться записанные в нём редиректы.

Вот содержимое .htaccess, которое следует записать для Angular:

 RewriteEngine On RewriteCond %% -f [OR] RewriteCond %% -d RewriteRule ^ - [L] RewriteRule ^ /index.html 

Если редиректы не выполняются, то следует выполнить команду:

Тогда мы включим модуль mod_rewrite и отработает условный оператор в файле.

Добавление пользователя MySQL

Если вы устанавливали MAMP, то логин у пользователя будет root и пароль тоже root.

При необходимости, для PhpMyAdmin можно создать нового суперпользователя.

Для этого следует запустить MySQL со следующими ключами:

Будет предложено ввести пароль, вводим root, попадаем в консоль в которой:

Создаём нового пользователя с паролем:

CREATE USER 'пользователь'@'localhost' IDENTIFIED BY 'пароль';

Добавляем ему все права:

GRANT ALL PRIVILEGES ON *.* TO 'пользователь'@'localhost' WITH GRANT OPTION;

Обновляем права:

Изменения в Angular

В папку src следует поместить файл .htaccess, в котором записан текст, приведённый ранее.

Также добавить папку src/php, в которую мы будем складывать скрипты на PHP, которые будут делать запросы к базе данных и возвращать необходимые выборки программе на Angular.

Откорректируем angular.json, находящийся в корне проекта. Добавим доступ к созданному нами ранее каталогу php и к файлу .htaccess в assets:

"assets": [ "src/favicon.ico", "src/assets", "src/php", "src/.htaccess" ],

Изменим каталог вывода собранных файлов, на директорию, из которой берёт скрипты apache:

Если вы используете MAMP на Windows, то путь к папке по умолчанию будет следующим:

Запуск сайта

Теперь выполним отладочный запуск сайта. Для этого воспользуемся не командой ng serve , а следующей:

Теперь, если всё было сделано правильно, то должно работать!

Публикация

Конечно, это только отладочный запуск. Для публикации следует почистить код от ненужных отладочных команд, а потом его собрать с помощью ng build –prod . Также можно задать директорию куда будет собираться всё прямо из командной строки, используя ключ –outputPath=путь . Таким образом можно задать путь куда следует собирать проект не из angular.json (через который мы этот путь изменяли выше).

Источник

Оцените статью