I am learning Angularjs and I created simple form. Actually i am PHP developer so i preferred to use php as a server side scripting language. I am unable to submit the data to server, i tried so many methods but those are very complex if i am trying in standard method Angularjs is not working please check my code, and give me best method to work with angularjs, jquery and php. help me!
我正在学习Angularjs,我创建了简单的表单。其实我是PHP开发人员所以我更喜欢使用php作为服务器端脚本语言。我无法将数据提交给服务器,我尝试了很多方法,但是如果我尝试使用标准方法Angularjs不能正常工作请检查我的代码,并给我最好的方法来处理angularjs,jquery和php。帮我!
angular.module("mainModule", [])
.controller("mainController", function($scope, $http) {
$scope.person = {};
$scope.serverResponse = '';
$scope.submitData = function() {
var config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
$http.post("server.php", $scope.person, config)
.success(function(data, status, headers, config) {
$scope.serverResponse = data;
})
.error(function(data, status, headers, config) {
$scope.serverResponse = "SUBMIT ERROR";
});
};
});
<?php
if (isset($_POST["person"]))
{
// AJAX form submission
$person = json_decode($_GET["person"]);
$result = json_encode(array(
"receivedName" => $person->name,
"receivedEmail" => $person->email));
} else
{
$result = "INVALID REQUEST DATA";
}
echo $result;
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<form name="personForm1" novalidate ng-submit="submitData()">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />
{{person.name}}
<br />
<label for="email">email:</label>
<input id="email" type="text" name="email" ng-model="person.email" data-parsley-type="email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
<br />
<div>
{{$scope.serverResponse}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!--<script type="text/javascript" src="script/parsley.js"></script>
<script src="script.js"></script>-->
</body>
</html>
3 个解决方案
#1
1
Updated, this is code that was just tested with php and Apache - and it works. I also changed your server.php file like below. The file was created based on AngularJS Hub's Server Calls sample. The same source was used to create mainController.js' $http.post(...) method call so that it successfully posts data to the server.
更新了,这是刚刚用php和Apache测试的代码 - 它可以工作。我也改变了你的server.php文件,如下所示。该文件是基于AngularJS Hub的Server Calls示例创建的。使用相同的源创建mainController.js'$ http.post(...)方法调用,以便它成功地将数据发布到服务器。
Screenshot (after submit)
截图(提交后)
server.php
server.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$result = "POST request received!";
if (isset($_GET["name"]))
{
$result .= "\nname = " . $_GET["name"];
}
if (isset($_GET["email"]))
{
$result .= "\nemail = " . $_GET["email"];
}
if (isset($HTTP_RAW_POST_DATA))
{
$result .= "\nPOST DATA: " . $HTTP_RAW_POST_DATA;
}
echo $result;
}
?>
personForm.html
personForm.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<form name="personForm1" validate ng-submit="submit()">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />
{{person.name}}
<br />
<label for="email">email:</label>
<input id="email" type="text" name="email" ng-model="person.email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
<br />
<div>
{{serverResponse}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="mainController.js"></script>
<!--<script type="text/javascript" src="script/parsley.js"></script>
<script src="script.js"></script>-->
</body>
</html>
mainController.js
mainController.js
angular.module("mainModule", [])
.controller("mainController", function ($scope, $http)
{
$scope.person = {};
$scope.serverResponse = "";
$scope.submit = function ()
{
console.log("form submit");
var params = {
name: $scope.person.name,
email: $scope.person.email
};
var config = {
params: params
};
$http.post("server.php", $scope.person, config)
.success(function (data, status, headers, config)
{
console.log("data " + data + ", status "+ status + ", headers "+ headers + ", config " + config);
$scope.serverResponse = data;
console.log($scope.serverResponse);
})
.error(function (data, status, headers, config)
{ console.log("error");
$scope.serverResponse = "SUBMIT ERROR";
});
};
});// JavaScript source code
Alternative way, with JSON handling:
替代方式,使用JSON处理:
server_json.php
server_json.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
/* code source: http://*.com/a/22852178/2048391 */
$data = array();
$json = file_get_contents('php://input'); // read JSON from raw POST data
if (!empty($json)) {
$data = json_decode($json, true); // decode
}
print_r($data);
}
?>
Screenshot (after submit)
截图(提交后)
#2
2
It seems from your code that you misunderstood some concepts.
你的代码似乎误解了一些概念。
- You're not using jQuery at all - you can remove it unless parsely (not familiar with this one...) requires it
- 你根本就没有使用jQuery - 你可以删除它,除非解析(不熟悉这个......)需要它
- All HTML tags besides the
DOCTYPE
should be inside the roothtml
tag. It's recommended to add JS at the bottom of thebody
tag which will (conceptually) contribute to page load performance. - 除DOCTYPE之外的所有HTML标记都应位于根html标记内。建议在body标签的底部添加JS,这将(在概念上)有助于提高页面加载性能。
- The order of JS you import is important and should be by dependencies (eg: AngularJS can uses jQuery only if it's included but in your case angular doesn't know about it since the jQuery is added after AngularJS which causes Angular to build its jq lite instead)
- 你导入的JS的顺序是重要的,应该是依赖的(例如:AngularJS只有在包含它时才能使用jQuery但在你的情况下,angular不知道它,因为在AngularJS之后添加jQuery导致Angular构建它的jq lite代替)
- You added a
submitData
to your controller's scope but you never call it - your intention was probably to use it when the user submits the form so you need to removeaction
andmethod
attributes from the form and addng-submit
:<form name="personForm1" method="post" novalidate ng-submit="submitData(person, 'thePropNameOnWhichYouWantToSaveTheReturnedData')">
. Both arguments are redundant since you have them on the$scope
. - 您向控制器的范围添加了一个submitData,但您从未调用它 - 您的意图可能是在用户提交表单时使用它,因此您需要从表单中删除操作和方法属性并添加ng-submit:
- The
config
argument sent with$http
service is used for configurations, not data. Read here: Angular $http - 使用$ http服务发送的config参数用于配置,而不是数据。在这里阅读:Angular $ http
- the default behavior of the
$http
is sending JSON as the request's body. It seems that you expect a form on your PHP code. This can be changed in theconfig
for example, or you can learn how to deserialize JSONs on PHP (sorry, I don't know PHP). - $ http的默认行为是发送JSON作为请求的正文。您似乎希望PHP代码上有一个表单。例如,这可以在配置中更改,或者您可以学习如何在PHP上反序列化JSON(抱歉,我不知道PHP)。
- Add the property on which you want to save the data to the
$scope
so it could be rendered. - 将要保存数据的属性添加到$ scope,以便可以呈现它。
Fixed client code suggestion:
修复了客户端代码建议:
angular.module("mainModule", [])
.controller("mainController", function($scope, $http) {
$scope.person = {};
$scope.serverResponse = '';
$scope.submitData = function() {
// Let's say that your server doesn't expect JSONs but expects an old fashion submit - you can use the `config` to alter the request
var config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
$http.post("server.php", $scope.person, config) // You can remove the `config` if the server expect a JSON object
.success(function(data, status, headers, config) {
$scope.serverResponse = data;
})
.error(function(data, status, headers, config) {
$scope.serverResponse = "SUBMIT ERROR";
});
};
});
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<form name="personForm1" novalidate ng-submit="submitData()">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />
{{person.name}}
<br />
<label for="email">email:</label>
<input id="email" type="text" name="email" ng-model="person.email" data-parsley-type="email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
<br />
<div>
{{$scope.serverResponse}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!--<script type="text/javascript" src="script/parsley.js"></script>
<script src="script.js"></script>-->
</body>
</html>
You should also read some more on AngularJS docs and maybe do their full tutorial. It's extremely helpful
您还应该阅读更多关于AngularJS文档的内容,或者阅读完整的教程。这非常有帮助
#3
1
You're using angular form and posting data from controller internally then you should not suppose to be mention action="server.php" method="post"
because you are going to do this call from controller i.e. $http.post('server.php')
.
你正在使用角形式并在内部发布控制器数据然后你不应该提到action =“server.php”method =“post”因为你要从控制器那里做这个调用,即$ http.post('server .PHP“)。
Just add ng-submit="submitData(person, 'result')"
directive in your form tag, that will call your controller method which is posting data and your code will start working.
只需在表单标记中添加ng-submit =“submitData(person,'result')”指令,它将调用发布数据的控制器方法,您的代码将开始工作。
HTML
HTML
<form name="personForm1" novalidate ng-submit="submitData(person, 'result')">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />{{person.name'}}
<label for="email">Last name:</label>
<input id="email" type="text" name="email" ng-model="person.email" data-parsley-type="email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
Hope this could help you. Thanks.
希望这可以帮到你。谢谢。
#1
1
Updated, this is code that was just tested with php and Apache - and it works. I also changed your server.php file like below. The file was created based on AngularJS Hub's Server Calls sample. The same source was used to create mainController.js' $http.post(...) method call so that it successfully posts data to the server.
更新了,这是刚刚用php和Apache测试的代码 - 它可以工作。我也改变了你的server.php文件,如下所示。该文件是基于AngularJS Hub的Server Calls示例创建的。使用相同的源创建mainController.js'$ http.post(...)方法调用,以便它成功地将数据发布到服务器。
Screenshot (after submit)
截图(提交后)
server.php
server.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$result = "POST request received!";
if (isset($_GET["name"]))
{
$result .= "\nname = " . $_GET["name"];
}
if (isset($_GET["email"]))
{
$result .= "\nemail = " . $_GET["email"];
}
if (isset($HTTP_RAW_POST_DATA))
{
$result .= "\nPOST DATA: " . $HTTP_RAW_POST_DATA;
}
echo $result;
}
?>
personForm.html
personForm.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<form name="personForm1" validate ng-submit="submit()">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />
{{person.name}}
<br />
<label for="email">email:</label>
<input id="email" type="text" name="email" ng-model="person.email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
<br />
<div>
{{serverResponse}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="mainController.js"></script>
<!--<script type="text/javascript" src="script/parsley.js"></script>
<script src="script.js"></script>-->
</body>
</html>
mainController.js
mainController.js
angular.module("mainModule", [])
.controller("mainController", function ($scope, $http)
{
$scope.person = {};
$scope.serverResponse = "";
$scope.submit = function ()
{
console.log("form submit");
var params = {
name: $scope.person.name,
email: $scope.person.email
};
var config = {
params: params
};
$http.post("server.php", $scope.person, config)
.success(function (data, status, headers, config)
{
console.log("data " + data + ", status "+ status + ", headers "+ headers + ", config " + config);
$scope.serverResponse = data;
console.log($scope.serverResponse);
})
.error(function (data, status, headers, config)
{ console.log("error");
$scope.serverResponse = "SUBMIT ERROR";
});
};
});// JavaScript source code
Alternative way, with JSON handling:
替代方式,使用JSON处理:
server_json.php
server_json.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
/* code source: http://*.com/a/22852178/2048391 */
$data = array();
$json = file_get_contents('php://input'); // read JSON from raw POST data
if (!empty($json)) {
$data = json_decode($json, true); // decode
}
print_r($data);
}
?>
Screenshot (after submit)
截图(提交后)
#2
2
It seems from your code that you misunderstood some concepts.
你的代码似乎误解了一些概念。
- You're not using jQuery at all - you can remove it unless parsely (not familiar with this one...) requires it
- 你根本就没有使用jQuery - 你可以删除它,除非解析(不熟悉这个......)需要它
- All HTML tags besides the
DOCTYPE
should be inside the roothtml
tag. It's recommended to add JS at the bottom of thebody
tag which will (conceptually) contribute to page load performance. - 除DOCTYPE之外的所有HTML标记都应位于根html标记内。建议在body标签的底部添加JS,这将(在概念上)有助于提高页面加载性能。
- The order of JS you import is important and should be by dependencies (eg: AngularJS can uses jQuery only if it's included but in your case angular doesn't know about it since the jQuery is added after AngularJS which causes Angular to build its jq lite instead)
- 你导入的JS的顺序是重要的,应该是依赖的(例如:AngularJS只有在包含它时才能使用jQuery但在你的情况下,angular不知道它,因为在AngularJS之后添加jQuery导致Angular构建它的jq lite代替)
- You added a
submitData
to your controller's scope but you never call it - your intention was probably to use it when the user submits the form so you need to removeaction
andmethod
attributes from the form and addng-submit
:<form name="personForm1" method="post" novalidate ng-submit="submitData(person, 'thePropNameOnWhichYouWantToSaveTheReturnedData')">
. Both arguments are redundant since you have them on the$scope
. - 您向控制器的范围添加了一个submitData,但您从未调用它 - 您的意图可能是在用户提交表单时使用它,因此您需要从表单中删除操作和方法属性并添加ng-submit:
- The
config
argument sent with$http
service is used for configurations, not data. Read here: Angular $http - 使用$ http服务发送的config参数用于配置,而不是数据。在这里阅读:Angular $ http
- the default behavior of the
$http
is sending JSON as the request's body. It seems that you expect a form on your PHP code. This can be changed in theconfig
for example, or you can learn how to deserialize JSONs on PHP (sorry, I don't know PHP). - $ http的默认行为是发送JSON作为请求的正文。您似乎希望PHP代码上有一个表单。例如,这可以在配置中更改,或者您可以学习如何在PHP上反序列化JSON(抱歉,我不知道PHP)。
- Add the property on which you want to save the data to the
$scope
so it could be rendered. - 将要保存数据的属性添加到$ scope,以便可以呈现它。
Fixed client code suggestion:
修复了客户端代码建议:
angular.module("mainModule", [])
.controller("mainController", function($scope, $http) {
$scope.person = {};
$scope.serverResponse = '';
$scope.submitData = function() {
// Let's say that your server doesn't expect JSONs but expects an old fashion submit - you can use the `config` to alter the request
var config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
$http.post("server.php", $scope.person, config) // You can remove the `config` if the server expect a JSON object
.success(function(data, status, headers, config) {
$scope.serverResponse = data;
})
.error(function(data, status, headers, config) {
$scope.serverResponse = "SUBMIT ERROR";
});
};
});
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<form name="personForm1" novalidate ng-submit="submitData()">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />
{{person.name}}
<br />
<label for="email">email:</label>
<input id="email" type="text" name="email" ng-model="person.email" data-parsley-type="email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
<br />
<div>
{{$scope.serverResponse}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!--<script type="text/javascript" src="script/parsley.js"></script>
<script src="script.js"></script>-->
</body>
</html>
You should also read some more on AngularJS docs and maybe do their full tutorial. It's extremely helpful
您还应该阅读更多关于AngularJS文档的内容,或者阅读完整的教程。这非常有帮助
#3
1
You're using angular form and posting data from controller internally then you should not suppose to be mention action="server.php" method="post"
because you are going to do this call from controller i.e. $http.post('server.php')
.
你正在使用角形式并在内部发布控制器数据然后你不应该提到action =“server.php”method =“post”因为你要从控制器那里做这个调用,即$ http.post('server .PHP“)。
Just add ng-submit="submitData(person, 'result')"
directive in your form tag, that will call your controller method which is posting data and your code will start working.
只需在表单标记中添加ng-submit =“submitData(person,'result')”指令,它将调用发布数据的控制器方法,您的代码将开始工作。
HTML
HTML
<form name="personForm1" novalidate ng-submit="submitData(person, 'result')">
<label for="name">First name:</label>
<input id="name" type="text" name="name" ng-model="person.name" required />
<br />{{person.name'}}
<label for="email">Last name:</label>
<input id="email" type="text" name="email" ng-model="person.email" data-parsley-type="email" required />
<br />
<br />
<button type="submit">Submit</button>
</form>
Hope this could help you. Thanks.
希望这可以帮到你。谢谢。