Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP POST using Angular.js

I'm new to the scene and I want to use Angular.js to make an HTTP POST request. I'm accessing PHP scripts which have parameters that are just POST variables. What gets returned from each script is a JSON string. Normally in an HTML form you can make such a request like:

<form method="post" action="url.php">
<input name="this">
<input name="that">
<input value="Submit">
</form>

Depending on your input and after you click submit, JSON data1 will return something like this: { "code" : 1 }

I have no access to the scripts or to the servers that hosts them.

I was wondering if it's possible for Angular.js to read the JSON data1, match that data1 to what they're defined in my JSON data2, and then output them to my view (<pre>data2</pre>).

For example, if { "code" : 1 } is retrieved, I want my JSON to output the value for code #1:

{ "code" : [
  { 1: "User already logged in." }, 
  { 2: "Wrong parameters, try again."}, 
  { 3: "etc., etc." }
 ] 
};

Here's my attempt:

<form ng-controller="PhpCtrl" name="f1">
<input type="text" name="name">
<input type="text" name="password">
<pre ng-model="codeStatus">{{codeStatus}}</pre>
<input type="submit" ng-click="add()" value="Submit">
</form>

function PhpCtrl($scope, $http, $templateCache) {
    $scope.method = 'POST';
    $scope.url = 'url.php';
    $scope.codeStatus = "";

    $scope.add = function() {

        $http({
            method: $scope.method, 
            url: $scope.url,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},  
            cache: $templateCache
        }).
        success(function(response) {
            $scope.codeStatus = response.data;
        }).
        error(function(response) {
            $scope.codeStatus = response || "Request failed";
        });
        return false;   
    };
}

All it's posting so far to the view is "Request failed" lol, although it's processing HTTP/1.1 200. I know I still have a ways to go but I would appreciate any help. Once I figure out how to post the proper JSON data1 to the view, the next step is matching and outputting the appropriate data2. Thank you in advance!

like image 853
matenji Avatar asked Mar 29 '13 16:03

matenji


People also ask

What does HTTP POST return angular?

HttpClient. post() method is an asynchronous method that performs an HTTP post request in Angular applications and returns an Observable. HttpClient. post() has a type parameter similar to the HttpClient. get() request, through which we can specify the expected type of the data from the server.

How do we pass data and get data using http in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

Can we use Ajax in AngularJS?

The AngularJS provides a control service named as AJAX – $http, which serves the task for reading all the data that is available on the remote servers. The demand for the requirement of desired records gets met when the server makes the database call by using the browser. The data is mostly needed in JSON format.

What is $resource in AngularJS?

Overview. A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service. Requires the ngResource module to be installed.


2 Answers

Acctually the problem is in the backend with PHP you don't retrieve the posted data like usual, this worked for me:

function PhpCtrl($scope, $http, $templateCache) {
  var method = 'POST';
  var url = 'url.php';
  $scope.codeStatus = "";
  $scope.add = function() {
    var FormData = {
      'name' : document.f1.name.value,
      'password' : document.f1.password.value
    };
    $http({
      method: method,
      url: url,
      data: FormData,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      cache: $templateCache
    }).
    success(function(response) {
        $scope.codeStatus = response.data;
    }).
    error(function(response) {
        $scope.codeStatus = response || "Request failed";
    });
    return false;
  };
}

in the PHP file:

$data = json_decode(file_get_contents("php://input"));
echo $data->name;

Hope this help.

like image 121
Yahya KACEM Avatar answered Oct 06 '22 18:10

Yahya KACEM


Rather old post... but I figure my solution might come in handy for others as well.

I did not like the

json_decode(file_get_contents("php://input"));

solution... Basically because it seems against good practice (I might be wrong on this)

This is how I got it solved (adapted to the example above)

function PhpCtrl($scope, $http, $templateCache) {
  var method = 'POST';
  var url = 'url.php';
  $scope.codeStatus = "";
  $scope.add = function() {
    var FormData = {
      'name' : document.f1.name.value,
      'password' : document.f1.password.value
    };
    $http({
      method: method,
      url: url,
      data: $.param({'data' : FormData}),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      cache: $templateCache
    }).
    success(function(response) {
        $scope.codeStatus = response.data;
    }).
    error(function(response) {
        $scope.codeStatus = response || "Request failed";
    });
    return false;
  };
}

once this done

data: $.param({'data' : FormData}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},

you can access the data you normally would in PHP

$data = $_POST['data'];
like image 21
dGo Avatar answered Oct 06 '22 18:10

dGo