Angular Post Request to PHP

Sending Post data from angularjs to PHP code is one of the tedious task and when I search it on Google I found posts which either too complex or not well written to understand concept properly.

I have solved the issue with less line of code and in more understanding and expressive way.

LIVE DEMO DOWNLOAD

You can clone the repository using

git clone https://github.com/codeforgeek/angular-post-php.git

Before heading to Angular HTTP Post let me show you how we do http.post call in JQuery. Here is a code snippet to do that.

$.post("filename.php",{var1: data, var2: data},function(data){
//Do something with data return from PHP file.
});

In PHP code we use $_POST global variable to access var1,var2. As simple as that. Problem arise with Angular because POST method which angular uses send data using JSON. So in PHP Script if we use $_POST directly we will not be able to receive POST data.

Let’s create one angular project and in that one simple Login form consist of email and password field. I hope you have read basic angularjs tutorial and know how to setup angular project. If not let me give you a quick review.

Very first thing you will need is angularjs library which you can either download or add using CDN, up to you. I use to download it and add it in local folder.

Link : Download Angularjs library (copy and paste the code in angular.js file)

Attach it to your project using

<script src="angular.js"></script>

before <head> section.

Now let’s create our login form in HTML. Under the section of your HTML page. Copy paste these code.

<div id="container">
            <div id="login" ng-app='angular_post_demo' ng-controller='sign_up'>
                <input type="text" size="40" ng-model="email"><br>
                <input type="password" size="40" ng-model="password"><br>
                <button ng-click="check_credentials()">Login</button><br>
                <span id="message"></span>
            </div>
</div>

We have name our angular app as “angular_post_demo” and controller as “sign_up”. Let’s create our app.js file to initialize angular app. Create file name as “app.js” and put this code in it.

app.js
var app = angular.module('angular_post_demo', []);

Done ! We have initiated our app. let’s code some JavaScript to deal with form handling. Create another file as “home.js” and put these code in it.

home.js
app.controller('sign_up', function ($scope, $http) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/

$scope.check_credentials = function () {

document.getElementById("message").textContent = "";

var request = $http({
    method: "post",
    url: window.location.href + "login.php",
    data: {
        email: $scope.email,
        pass: $scope.password
    },
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
    document.getElementById("message").textContent = "You have login successfully with email "+data;
});
}
});

Note: add these files using <script> tag under <head> section.

Major change is in the PHP file. Here is how to read POST data in PHP sent from Angular.

login.php
<?php
   /*
   * Collect all Details from Angular HTTP Request.
   */

    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    @$email = $request->email;
    @$pass = $request->pass;
    echo $email; //this will go back under "data" of angular call.
    /*
     * You can use $email and $pass for further work. Such as Database calls.
    */
   
?>

file_get_contents() reads the file and convert it into string and by using json_decode() we can determine which part of data we would like to access.

You can download the code from Github either by cloning it or zip file. To run it paste it in “HTDOCS” folder of XAMPP and hit using browser url.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

64 Comments

  1. Hi to every body, it’s my first pay a visit of this web site; this web site includes awesome and in fact excellent data designed for visitors.

  2. Hi guys,
    This is an excellent tutorial, very simple, very clear and very powerful
    I appreciate your knowledge.
    I also have a question: how can I tell if there is a connection problem with the server side?, I mean, can I add something like:
    request.failure(function (data) {
    $scope.message = “Server error”;
    });
    Thanks in advance

  3. This is a following from my previous message… if I enter the email and password once, everything works perfect but I try again, then I have no response from the server side, there is no answer and {{message}} keeps blanks, am I doing something wrong?
    Thanks again
    Oscar

    1. May be i have some bug in demo code. Basic aim was to show that POST request is going to PHP file and something coming back from response. I think i should update the demo to more user friendly one.

      1. Thank you Shahid, I really appreciate your response and it will be great if you can upgrade your demo.
        Can I send my code to you? because I can’t make it work properly. When I call the $scope.user (in my app) the controller doesn’t recognize the value of user, I was trying to send values from myForm.user.value but can’t make it work.
        BTW, I’m using bootstrap
        Thanks again
        Best regards

  4. HOw will you handle failures ( if credentials are invalid i.e username and password not present in database) and expose that message in {{errorMessage}}

  5. Hi,

    I want to know if we can use this same method to get map coords from database. For example, if we have stored specific coords in a database as markers and our purpose is to populate the most relevant marker according to user search.

    Can we bind search and make a POST call for the right coord?

  6. Thank you, thank you, thank you!

    This was so helpful. I was beating my head against a wall trying to figure out how to simply post stuff, so that PHP could insert into my database. I had a script working with jQuery, but I decided to switch to Ionic and AngularJS. This got me where I needed to go.

    When I implemented for my purposes, I was struggling to get hidden fields to work, as that seems to be a huge problem for many in AngularJS. In my particular use case, I thought outside of the box… why did I need a hidden field? I was trying to include data from localStorage, so I just defined variables and posted those. I figured this out mostly from your example and a little bit of tweaking.

    I just wanted to add the tidbit in case it helps someone else trying to do similar!

  7. Thanks this is very handy,

    I had to add

    header(‘Access-Control-Allow-Origin: *’);

    to login.php script to make it work though across domains.

  8. Hi!
    I see your cool code, but dont work for me. I have an site, upload these files (download link) an empty folder, and dont work. Need install node js to work?
    Thx

  9. Hi Shahid,

    Thanks excellent tutorial. when i used with nodejs instead of php I faced the problem while parsing. So if anyone use node js please change headers: { ‘Content-Type’: ‘application/json’ } . Thanks once again

  10. Thank you so much for this example, it helped me a lot too!

    Your code works with angular 1.2.15 but not in 1.3.15, do you know why?

  11. hmmm dunno about every one but it’s not working for me … maybe because angular version is not the same …

  12. I am trying same sort of thing , but its not working..!!!
    in my case , login.php is not getting any data..
    Does this need any modication in php..
    anything like tht
    because on success i got a log message through js but php result doesnt show up

  13. Shahid, thanks for sharing this… one question: the tutorial says how to send POST request to Node.js but it shows how to send to PHP, is that ok?

  14. why have you used jquery in angular for http where as angular already has its own version of code to do so, though it was quite informative

  15. Hi! Thanks for this tutorial. How do i pass values from checkboxes to php? Do i have to set empty scope variable array in my controller? Please guide me. Thanks

  16. I looked at the console and the URL was doubling up from the POST. if everything is on the same server your last if statement should look like this
    if (error === 0) {
    var request = $http({
    method: “POST”,
    url: “login.php”,
    data: {
    email: $scope.email,
    pass: $scope.password
    },
    headers: { ‘Content-Type’: ‘application/json’ }
    });

  17. Hello,
    And if I have multiple controllers with multiple data source? How can I get a specified value from 3 controllers with 3 different values?
    Thank you

  18. Good job Shahid. I’m following all your tutorial. You make us easy to understand each framework and present it in such a simple as possible. Bravo

  19. Hii,
    I tried this code…..when i click login button i got a response like this-
    “You have login successfully with email “and after this whole php file is printed as it is…..i think it should only print the email…..why this problem occurs….will you please elaborate?
    Thankyou

  20. Great Post! I didn’t know angualr PHP is some different with usual PHP in getting POST parameters.
    So I was failing in using $_POST[‘arg’].
    Thanks a lot.

Leave a Reply

Your email address will not be published. Required fields are marked *