Angularjs将表单输入保存到php和Mysql


Angularjs save form input to php and Mysql

我在学习和构建angularjs应用程序时遇到了一个问题。我就是无法将表单数据保存到mysql。。。我花了好几个小时尝试了所有的东西,但都不起作用。

当使用该变量时,PHP文件向mysql表输入空查询。如果我使用静态信息,效果很好。

谢谢:)

app.controller('addMsgCtrl', function ($scope, $http) {
$scope.fill = function(add) {
var data = {
            addItem: $scope.addItem
        };
$http.post("msinput.php",{'data' : $scope.addItem})
        .success(function(data, status, headers, config){
            console.log("inserted Successfully");
        });
        };
});
$data = json_decode(file_get_contents("php://input"));
$addItem = mysql_real_escape_string($data->addItem);
mysql_connect("localhost", "username", "password") or die(mysql_error()); 
mysql_select_db("stran189_taskma") or die(mysql_error()); 
mysql_query("INSERT INTO message (addItem) VALUES ('$addItem')"); 
Print "Your information has been successfully added to the database."; 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form class="add-task" id="newTaskForm" ng-controller="addMsgCtrl" novalidate ng-submit="fill()">
        <div class="form-actions">
          <div class="input-group">
            <input ng-model="addItem" class="form-control" type="text" name="addItem" placeholder="Ny anteckning" />
            <div class="input-group-btn"><button class="btn btn-default" type="submit">
              <i class="glyphicon glyphicon-plus"></i></button>
          </div>
        </div>
        </div> 
      </form>

回复JS:"插入成功!"NET:"POST 200 OK msinput.php"请求标头:"主机:(myUrl)用户代理:Mozilla/5.0(Macintosh;Intel Mac OS X 10.11;rv:44.0)Gecko/20100101 Firefox/44.0接受:application/json,text/plain,/接受语言:en-US,en;q=0.5接受编码:gzip,deflate引用人:(myUrl)内容类型:application/json;charset=utf-8内容长度:2连接:保持活动"

响应标头:连接:保持活动内容长度:62内容类型:text.html日期:2015年12月7日星期一21:36:53 GMT保持活动:超时=5,最大值=100服务器:Apache/2.4.10(Unix)OpenSSL/0.9.8e-ips-rhel5 mod_bwlimited/1.4Vary:用户代理X-Powered-Bby:PHP/5.4.37

我对您的控制器代码有点困惑,但在我看来,您准备了要发送到服务器的var数据。如果这是真的,你必须$http.post("msinput.php",{'data':$scope.data})…

在fill()日志数据内部。看看里面有没有人。这个的变化

$http.post("msinput.php",{'data' : $scope.addItem})

到这个

$http.post("msinput.php",{'data' : data})

然后检查网络XHR,查看数据是否正确发送到服务器。

此外,为了获得更多关于服务器回复内容的信息,您也可以使用此方法并记录错误:

// Simple GET request example:
$http({
  method: 'POST',
  url: 'msinput.php'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
 }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
});

首先确保您的数据存在:

在Firefox中打开Firebug,选择控制台选项卡

在Firefox中导航到您的表格,填写表格并提交。

控制台中的最后一行应显示:

POST http://..../msinput.php

点击这个并查看POST&JSON选项卡,它将显示每个字段的所有输入数据。任何丢失的东西显然都不会进入你的数据库。

一旦你知道你的数据正在离开,那么你就可以弄清楚为什么它没有到达。

我还强烈建议您更改为PDO并停止使用mysql函数,因为它现在已被弃用。

好的,现在你知道你的表单中的数据是通过你的帖子操作离开的。

在msinput.php中执行以下

var_dump( file_get_contents(http://input) );

查看firebug控制台中返回的内容。