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

74 thoughts on “Angular Post Request to PHP”

      1. Thank you a lot, I just got crazy all of the day trying to figure out why I could not get $POST values in php from angular http.post request. You made my day!

    1. Old post but I have had a heck of a time finding this solution! Why is this not better published, or was I looking for the wrong terms? THANKS!

  1. Hello to all, the contents existing at this website are truly amazing for people experience, well, keep up the nice work fellows.

  2. I am really pleased to read this web site posts which includes plenty of valuable information, thanks for providing these information.

  3. 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.

    1. Hi Jannette,
      This is Shahid – admin of this web site. I am really thankful and glad to you about the way you have described my site.
      Keep visiting !

  4. 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

  5. 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

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

    1. Hi thanks for comment Balaji. Demo was to just show how to call PHP file with AngularJS, that’s why i didn’t put much validation on the form.

  7. This post is in fact a nice one it assists new net viewers, who are wishing in favor of blogging.

  8. 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?

  9. 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!

  10. 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.

  11. 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

  12. vidhyasankar.g

    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

  13. hi very nice tuto (y)
    i m working with ionic . what should I modify to connect to PHP ??

  14. 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?

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

    1. Yes but while coding this i was not able to get the data. After adding header i got the data.

  16. 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

  17. Its good. I learnt it from here. Please update some more stuff relating to $resource factory.

  18. 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?

  19. 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

  20. 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

    1. Shahid (UnixRoot) Shaikh

      I think with newer version, Yes. Keep an empty array with scope and use that to bind the data of checkbox.

  21. Andrew S Southwick

    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’ }
    });

  22. 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

  23. 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

  24. 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

  25. 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.

Comments are closed.