4

I'm new in AngularJS and following some tutorials I was able to create a simple page and a simple form.

The problem is that every time I submit the form seems that the script is sending empty data.

This is my html:

<div class="jumbotron text-center">
        <h1>Contatti</h1>

        <p ng-show="message">{{ message }}</p>
    </div>

<div class="row">
    <div class="col-lg-8">
        <form ng-submit="processForm()">
            <div class="form-group" ng-class="{ 'has-error' : errorName }">
                <label>Nome</label>
                <input type="text" name="name" class="form-control" placeholder="chris" ng-model="formData.name">
                 <span class="help-block" ng-show="errorName">{{ errorName }}</span> 
            </div>
            <button type="submit" class="btn btn-large">
                Salva
            </button>
        </form>
    </div>
</div>

<pre>
    {{ formData }}
</pre>

This is the js:

//Creo il modulo e includo ngRoute come dipendenza
var scotchApp = angular.module('scotchApp', ['ngRoute']);


//Configuro le routes
scotchApp.config(function($routeProvider){

    $routeProvider

        .when('/', {
            templateUrl: 'pages/home.html',
            controller: 'mainController'
        })

        .when('/chi-siamo', {
            templateUrl: 'pages/chi-siamo.html',
            controller: 'aboutController'
        })

        .when('/contatti', {
            templateUrl: 'pages/contatti.html',
            controller: 'contactController'
        });

});

//Creo il controller che gestisce la home
scotchApp.controller('mainController', function($scope){
    $scope.message = "Sono in home";
});

//Controller che gestisce la pagina chi-siamo
scotchApp.controller('aboutController', function($scope){
    $scope.message = "Sono in Chi siamo";
});


//Controller che gestisce la pagina contatti
scotchApp.controller('contactController', function($scope, $http){

    $scope.formData = {};

    $scope.processForm = function(){


        console.log($scope.formData);

        $http.post('process.php', $scope.formData)
             .success(
                function(data){

                    console.log(data);

                    if( data.success )
                    {
                        $scope.message = data.message;
                    }
                    else
                    {
                        $scope.errorName = data.errors.name;
                    }

                }
             );
    }
});

and this is a very simple php script:

<?php
// process.php

$errors = array();  // array to hold validation errors
$data = array();        // array to pass back data


// validate the variables ========
if (trim($_POST['name']) == '')
  $errors['name'] = 'Name is required.';

// return a response ==============

// response if there are errors
if ( count($errors) > 0 ) {

  // if there are items in our errors array, return those errors
  $data['success'] = false;
  $data['errors']  = $errors;
} else {

  // if there are no errors, return a message
  $data['success'] = true;
  $data['message'] = 'Success!';
}

// return all our data to an AJAX call
echo json_encode($data);

Even if I write some data in my input in the console I get:

Object {success: false, errors: Object}
errors: Object
name: "Name is required."
__proto__: Object
success: false
__proto__: Object

Am I missing something?

4
  • I've updated my answer to include the reason below; Hope this helps. Commented May 14, 2015 at 16:28
  • try to print all POST <?php print_r($_POST); ?> to see what is wrong Commented May 14, 2015 at 16:28
  • Please show the code for processForm() Commented May 14, 2015 at 17:25
  • @BrentWashburne, just scroll the code and you'll see it. Commented May 14, 2015 at 17:53

2 Answers 2

4

you need to get the data in php as,

$data = json_decode(file_get_contents("php://input"));

$data->name  // to access name

OR

add the jquery and change the headers,

$http({
    url: "process.php",
    method: "POST",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param($scope.formData)
}).success(function(data, status, headers, config) {

}).error(function(data, status, headers, config) {

});

in php

$name= $_POST['name'];

if you need to change the headers of all ajax requests then do it in config block for EX,

app.config(['$httpProvider' , '$routeProvider', function ($httpProvider, $routeProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}])
Sign up to request clarification or add additional context in comments.

8 Comments

And also, it is possible to change a content-type in the AngularJS.
If I add the header section nothing change, same problem. If I add the $.param I get ReferenceError: $ is not defined
If I use file_get_content I get POST http://localhost:8888/Angularjs/process.php 500 (Internal Server Error)
its file_get_contents not file_get_content u missed last s i think :)
$.param is a jQuery function, as I know. So, if you don't have jQuery in the project, than you may try to find a replacement for it. something like this: stackoverflow.com/a/22583081/2737720
|
1

TL;DR Aha! since $scope.formData is an Object? Then do JSON.stringify().

TL;DR Aha! since $errors is an array? Then do json_encode().

JS:

$http.post('process.php', JSON.stringify( $scope.formData ) ) ...

PHP:

json_encode($errors);

Note:

write: JSON.stringify. json_encode()
read: JSON.parse(), json_decode()

As for AngularJS docs, it defaults in header settings ( *Note: dataType )

Setting HTTP Headers

The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

$httpProvider.defaults.headers.common (headers that are common for all requests):
Accept: application/json, text/plain, * / *
$httpProvider.defaults.headers.post: (header defaults for POST requests)
Content-Type: application/json
$httpProvider.defaults.headers.put (header defaults for PUT requests)
Content-Type: application/json

Hope this helps.

2 Comments

The problem is that in process.php the $_POST is always empty
@ChristianGiupponi, i updated the answer on JSON,stringify( object ), since $scope.form is an object. See how that goes. Hope that helps.

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.