Programming

PHP에 AngularJS HTTP 게시 및 정의되지 않음

procodes 2020. 8. 8. 14:05
반응형

PHP에 AngularJS HTTP 게시 및 정의되지 않음


태그가있는 양식이 있습니다. ng-submit="login()

이 함수는 자바 스크립트에서 잘 호출됩니다.

function LoginForm($scope, $http)
{
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

    $scope.email    = "fsdg@sdf.com";
    $scope.password = "1234";

    $scope.login = function()
    {
        data = {
            'email' : $scope.email,
            'password' : $scope.password
        };

        $http.post('resources/curl.php', data)
        .success(function(data, status, headers, config)
        {
            console.log(status + ' - ' + data);
        })
        .error(function(data, status, headers, config)
        {
            console.log('error');
        });
    }
}

나는 PHP 파일에서 200 OK 응답 등을 얻고있다, 그러나, 반환 된 데이터는 것을 말하고 emailpassword정의되지 않은 있습니다. 이것은 내가 가진 모든 PHP입니다

<?php
$email = $_POST['email'];
$pass  = $_POST['password'];
echo $email;
?>

왜 내가 정의되지 않은 POST값을 얻는 지 아십니까?

편집하다

나는이 (아직 나이입니다) 인기 질문 것으로 보인다 이후 지적하고 싶었, .success그리고 .error사용되지 않으며 당신은 사용해야 .then@ 제임스 씨족이 commments에서 지적


angularjs는 .post()기본적으로 Content-type 헤더를 application/json. 양식 인코딩 된 데이터를 전달하기 위해이를 재정의하고 있지만 data적절한 쿼리 문자열을 전달하도록 값을 변경하지 않으므로 PHP가 $_POST예상대로 채워지지 않습니다 .

내 제안은 기본 angularjs 설정을 application/json헤더로 사용하고 PHP에서 원시 입력을 읽은 다음 JSON을 역 직렬화하는 것입니다.

다음과 같이 PHP에서 수행 할 수 있습니다.

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $request->email;
$pass = $request->password;

또는 $_POST기능에 크게 의존하는 경우 다음 과 같은 쿼리 문자열 email=someemail@email.com&password=somepassword을 구성하여 데이터로 보낼 수 있습니다. 이 쿼리 문자열이 URL로 인코딩되었는지 확인하십시오. 수동으로 빌드 한 경우 (같은 것을 사용하는 것과는 반대로 jQuery.serialize()) Javascript가 encodeURIComponent()트릭을 수행해야합니다.


init 파일의 시작 부분에서 서버 측에서 수행하고 매력처럼 작동하며 각도 또는 기존 PHP 코드에서 아무것도 할 필요가 없습니다.

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

API에서 개발 중이며 기본 컨트롤러가 있고 __construct () 메서드 내부에 다음이 있습니다.

if(isset($_SERVER["CONTENT_TYPE"]) && strpos($_SERVER["CONTENT_TYPE"], "application/json") !== false) {
    $_POST = array_merge($_POST, (array) json_decode(trim(file_get_contents('php://input')), true));
}

This allows me to simply reference the json data as $_POST["var"] when needed. Works great.

That way if an authenticated user connects with a library such a jQuery that sends post data with a default of Content-Type: application/x-www-form-urlencoded or Content-Type: application/json the API will respond without error and will make the API a little more developer friendly.

Hope this helps.


Because PHP does not natively accept JSON 'application/json' One approach is to update your headers and parameters from angular so that your api can use the data directly.

First, Parameterize your data:

data: $.param({ "foo": $scope.fooValue })

Then, add the following to your $http

 headers: {
     'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
 }, 

If all of your requests are going to PHP the parameters can be set globaly in the configuration as follows:

myApp.config(function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Angular Js Demo Code :-

angular.module('ModuleName',[]).controller('main', ['$http', function($http){

                var formData = { password: 'test pwd', email : 'test email' };
                var postData = 'myData='+JSON.stringify(formData);
                $http({
                        method : 'POST',
                        url : 'resources/curl.php',
                        data: postData,
                        headers : {'Content-Type': 'application/x-www-form-urlencoded'}  

                }).success(function(res){
                        console.log(res);
                }).error(function(error){
                        console.log(error);
        });

        }]);

Server Side Code :-

<?php


// it will print whole json string, which you access after json_decocde in php
$myData = json_decode($_POST['myData']);
print_r($myData);

?>

Due to angular behaviour there is no direct method for normal post behaviour at PHP server, so you have to manage it in json objects.


You need to deserialize your form data before passing it as the second parameter to .post (). You can achieve this using jQuery's $.param (data) method. Then you will be able to on server side to reference it like $.POST ['email'];


This is the best solution (IMO) as it requires no jQuery and no JSON decode:

Source: https://wordpress.stackexchange.com/a/179373 and: https://stackoverflow.com/a/1714899/196507

Summary:

//Replacement of jQuery.param
var serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
};

//Your AngularJS application:
var app = angular.module('foo', []);

app.config(function ($httpProvider) {
    // send all requests payload as query string
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return serialize(data);
    };

    // set all post requests content type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Example:

...
   var data = { id: 'some_id', name : 'some_name' };
   $http.post(my_php_url,data).success(function(data){
        // It works!
   }).error(function() {
        // :(
   });

PHP code:

<?php
    $id = $_POST["id"];
?>

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer


It took me hours to understand that while working with Angular and PHP. Post data was not going to PHP in $_POST

in PHP code do the following. - Create a variable $angular_post_params - Then do the following $angular_http_params = (array)json_decode(trim(file_get_contents('php://input')));

now you can access your parameters like you do from $_POST

$angular_http_params["key"]

in case you were wondering about javascript....this is what i used

    var myApp = angular.module('appUsers', []);
    //var post_params = $.param({ request_type: "getListOfUsersWithRolesInfo" });
    var dataObj = {
        task_to_perform: 'getListOfUsersWithRolesInfo'
    };

    myApp.controller('ctrlListOfUsers', function ($scope, $http) {
        $http({
            method: 'POST',
            dataType: 'json',
            url: ajax_processor_url,
            headers: {
                'Content-Type': 'application/json'
            },
            data: dataObj,
            //transformRequest: function(){},
            timeout: 30000,
            cache: false
        }).
        success(function (rsp) {
            console.log("success");
            console.log(rsp);
        }).
        error(function (rsp) {
            console.log("error");
        });
    });

참고URL : https://stackoverflow.com/questions/15485354/angularjs-http-post-to-php-and-undefined

반응형