6

I have a Raw form with some angularjs Validation,

<form name = "sform" novalidate="true">
<table border="0">
    <tr>
        <td>
            First name:
        </td>
        <td>
            <input type="text" name="fname" ng-model="fname" placeholder="First Name" required="true" ng-pattern="/^[A-Za-z]*$/">
        </td>
        <td ng-show="sform.fname.$invalid && !sform.fname.$pristine"  class="help-block">wrong name </td>
    </tr>

    <tr>
        <td>
            Last Name:
        </td>
        <td>
            <input type="text" ng-model="lname" placeholder="last Name" required="true" ng-pattern="/^[A-Za-z]*$/">
        </td>
        <td ng-show= "sform.lname.$invalid && !sform.lname.$pristine"  class="help-block">wrong Last name </td>
    </tr>
    <tr>
        <td>
            Email:
        </td>
        <td>
            <input type="email" ng-model="email" placeholder="email" required="true">
        </td>
        <td ng-show="sform.email.$invalid && !sform.email.$pristine"  class="help-block">wrong Email </td>
    </tr>
    <tr>
        <td>
            <button type="submit" ng-disabled="sform.$invalid" ng-click = "submitForm()">Submit</button>
        </td>
    </tr>       
</table>
</form>

And related .js files are

far_app.js

var farLogin = angular.module('far_login',[]);

far_formcontroler.js

farLogin.controller('far_formcontrol',['$scope','$http',function($scope,$http) {
    $scope.url='http://localhost/far_submit.php';
     var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

        // function to submit the form after all validation has occurred            
        $scope.submitForm = function() {
            alert('our form is amazing'+$scope.fname+' '+$scope.email+' '+$scope.lname); 
            // check to make sure the form is completely valid
            if ($scope.sform.$valid) {
                $http.post($scope.url,{"name": $scope.fname, "email": $scope.email, "lname": $scope.lname},config).
                 success(function() {
                            alert('our form is amazing'+$scope.fname+' '+$scope.email+' '+$scope.lname); 
                        })

            }
            else
            {
                alert('our form is not amazing');   
            }

        }

    }]);

And my php file is

<?php
header("Access-Control-Allow-Origin: *");
?>
<script type="text/javascript"> alert("this is php")</script>
<?php
?>

But the php script is not at all executing and their are no error in browser's console.

Where I'm going wrong?

Thank you.

15
  • Have you set controller somewhere in your html? Commented Apr 18, 2016 at 6:40
  • ya i did its inside div tag covering all the form Commented Apr 18, 2016 at 7:18
  • Can you see the http request to the PHP script inside the browser debugger? I dont know angular, but maybe its not accepting html content. Try raw javascript without tha html script tag. Commented Apr 23, 2016 at 10:07
  • Can you console log this {"name": $scope.fname, "email": $scope.email, "lname": $scope.lname} before your post request and let me know the output? also can you check the network request to see if the request is actually going through? Commented Apr 23, 2016 at 10:40
  • Object {name: "name", email: "[email protected]", lname: "lastname"} thsi is the output of console.log before sending request Commented Apr 23, 2016 at 10:46

1 Answer 1

6
+25

there are couple good threads on Angular $http post issues in SO itself, for example have a look at following thread: How do I POST urlencoded form data with $http in AngularJS? or this one : How can I post data as form data instead of a request payload?

Note: You need to run this using a web server locally. code below is working for me "a OK", I did following:

  • Downloaded the code you have provided
  • Save all of them in a local directory
  • Started php built in web server php -S 0.0.0.0:8181, accessed the index.html at : http://localhost:8181/ submitted the form and it returned me a json response : {"status":"OK","data":{"userid":null}}

Pastebin: far_app.js, index.html, far_login.php

I used PHP built in server just for the testing purpose, but, I highly recommend you use something like Wampp or Xampp on Windows to run this. You can manually configure your Apache/PHP/Mysql as well, but, Wampp/Xampp are pretty easy to install and get started with.

I've restructured the code a bit, something like following:

    angular.module('far_login',[])
.controller('far_formcontrol',['$scope','$http', function($scope, $http) {
    // function to submit the form after all validation has occurred            
    $scope.submitForm = function() {
        console.log('First Name : ' , $scope.fname);
        console.log('Email : ' , $scope.email);
        console.log('Last Name: ', $scope.lname); 
        // check to make sure the form is completely valid
        if ($scope.sform.$valid) {
            $http({
                url: 'http://localhost:8181/far_submit.php',
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                transformRequest: function(obj) {
                    var str = [];
                    for(var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                },
                data: {"name": $scope.fname, "email": $scope.email, "lname": $scope.lname}
            })
            .then(function(response) {
                console.log(response)
            })
            .catch(function  (error) {
                console.log(error);
            });

        } else {
            alert('our form is not amazing');   
        }
    };
}]);

this is based on Plunker from Angular doc, and the far_submit.php file like:

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

$data = [ 'status' => 'OK', 'data' => [ 'userid' => $autogeneratedUserId] ];
echo json_encode($data);

Make sure the the far_submit.php is accessible at http://localhost/far_submit.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.