0
votes

I am new to angular.js and am unable to get a simple POST request to work. I am using angular version 1.4.8. My request never makes it to the server. Instead, it appears the client errors out before making the request. I can't see what I'm doing wrong, even though I've read the documentation here: https://docs.angularjs.org/api/ng/service/$http#post. Here is the relevant error info I have (produced with the code example below):

{ "data": null, "status": -1, "config": { "method": "POST", "transformRequest": [ null ], "transformResponse": [ null ], "url": "http://localhost:4567/foo", "data": { "foo": "bar" }, "headers": { "Accept": "application/json, text/plain, /", "Content-Type": "application/json;charset=utf-8" } }, "statusText": "" }

And here is my code example. It reproduces the problem in both firefox and chrome, so this doesn't seem to be a browser quirk. Since I'm an angular newbie, this is likely something basic (but not obvious to me). Help appreciated ;)

<!DOCTYPE HTML>
<html lang="en-US">

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>

<body>
<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function ($scope, $http) {

        $scope.httpPost = function (postBody) {
            var successCallback = function (data, status, headers, config) {
                alert("post success");
            };

            var errorCallback = function (data, status, headers, config) {
                var responseJson = angular.toJson(data);
                $scope.theError = responseJson;
            };

            $http.post('http://localhost:4567/foo', postBody).then(successCallback, errorCallback);

        };

        var postBody = {"foo" : "bar"};
        $scope.httpPost(postBody);
    });
</script>

<div data-ng-app="myApp" data-ng-controller="customersCtrl">
    <pre>{{theError}}</pre>
</div>

</body>
</html>
1
could you provide more information on the client error? are you getting anything in either callback? - devonj
I converted the error to json. It is listed in the second paragraph of the questions. - thebiggestlebowski
I mean, did you print $scope.theError? (just making sure because it seems like you did) Or where did the error come from? Making sure it is a client error, because the JSON you posted seems like the request is fine / your code looks ok - devonj
The error was printed with this line: <pre>{{theError}}</pre> - thebiggestlebowski

1 Answers

0
votes

While I don't know the answer to your question, may I suggest what worked for me? I too am an Angular beginner. Also, have a look at John Papa's Angular guide for better code.

Front End

angular
    .module('app')
    .config(config);

function config($routeProvider) {
    $routeProvider.when('/add-job', {
        templateUrl: 'templates/add-job.view.html',
        controller: AddController,
        controllerAs: 'addCtrl'
    });
};

function AddController($http) {
    var that = this;

    that.add_new = function (job) {
        $http.post('api/add_job', that.job).success(function () {
            //alert("added!");
        });
    };
}

Back End - Slim framework

require 'vendor/autoload.php';

$app = new \Slim\App; 

$app->post('/add_job', 'addJob');

function addJob($request) {
    $job = json_decode($request->getBody());
    $sql = "INSERT INTO jobs (title, company, location) VALUES (:title, :company, :location)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);  
        $stmt->bindParam("title", $job->title);
        $stmt->bindParam("company", $job->company);
        $stmt->bindParam("location", $job->location);
        $stmt->execute();
        $job->id = $db->lastInsertId();
        $db = null;
        echo json_encode($job); 
    } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

View

<form novalidate name="AddNewForm" method="post" action="">

    <input type="text" ng-model="addCtrl.job.title" placeholder="Title" /><br/>
    <input type="text" ng-model="addCtrl.job.company" placeholder="Company" /><br/>
    <input type="text" ng-model="addCtrl.job.location" placeholder="Location" /><br/>

    <button ng-click="addCtrl.add_new(job)">Save!</button>

</form>