简体   繁体   English

Angular4 ng提交表格数据到PHP文件

[英]Angular4 ngsubmit form data to php file

I am trying to set a CRUD system with Angular4 and MySQL and PHP, for that i create a service file tables.service.ts 我正在尝试使用Angular4和MySQL和PHP设置CRUD系统,为此我创建了一个服务文件table.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class TablesService {

constructor(private http: Http) {
}
 // get table content
getTableContent() {
return this.http.get('http://localhost/Backend/tables.php')
    .map(res => res.json()
    );
 }
// post data to table
postTableContent(contents: any[]) {
  const headers = new Headers({'Content-Type': 'application/json'});
  console.log('form data \n' + JSON.stringify(contents));
  return this.http.post('http://localhost/Backend/postData.php',
      JSON.stringify(contents),
      {headers: headers}
   );
 }
}

And in my table.ts file i subscribed to this service: 在我的table.ts文件中,我订阅了此服务:

import {Component, OnInit, ViewChild, ViewEncapsulation} from 
 '@angular/core';
 import {TablesService} from '../../../services/tables.service';
 import {NgForm} from '@angular/forms';

 @Component({
 selector: 'app-table-choisie',
 templateUrl: './table-choisie.component.html',
 styleUrls: ['./table-choisie.component.css'],
 encapsulation: ViewEncapsulation.None
})
export class TableChoisieComponent implements OnInit {
 tableContents: any[];
 @ViewChild('f') signupForm: NgForm;

constructor(private tableContentsS: TablesService) { }

ngOnInit() {
// afficher le contenue d'une table
this.tableContentsS.getTableContent()
    .subscribe(
        (tableContents) => {
          console.log(tableContents);
          this.tableContents = tableContents;
        },
        (error) => console.log('Error ' + error)
    );
 }

// on submit
onSubmit(form: NgForm) {
    this.tableContentsS.postTableContent(form.value)
        .subscribe(
            (formContents) => console.log('Form Contents'+formContents),
            (error) => console.log(error)
        );
    // print form values to the console
    // console.log(JSON.stringify(form.value));
    this.signupForm.reset();
     }

  }

The Get method working fine, but i have difficulties in sending data to the server with the post method, i searched a lot and i did not find the right way to do that. Get方法可以正常工作,但是我很难使用post方法将数据发送到服务器,我进行了很多搜索,但没有找到正确的方法。

My postData.php file: 我的postData.php文件:

<?php   

 header('Access-Control-Allow-Origin:*');
 header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-
 Token');
 include('connexion.php');

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

And when i submit my form i have this output: 当我提交表格时,我得到以下输出: 在此处输入图片说明

I am really blocked and i dont know how to proceed 我真的被封锁了,我不知道如何进行

Thanks alot 非常感谢

try this 尝试这个

postTableContent(contents: any[]) {

  let formData:FormData = new FormData();

   formData.append('data', JSON.stringify(data));

  const headers = new Headers({'Content-Type': 'application/json'});
  console.log('form data \n' + JSON.stringify(contents));
  return this.http.post('http://localhost/Backend/postData.php',formData,{headers: headers});
 }
}

and in your php 并在您的PHP中

<?php   

 header('Access-Control-Allow-Origin:*');
 header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-
 Token');
 include('connexion.php');

 echo json_encode($_POST);
 ?>

I put this code in my php file: 我将此代码放在我的php文件中:

<?php  
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods: PUT, GET, POST, OPTIONS ");
header("Access-Control-Allow-Headers: Origin, X-Requested-Width, Content-
Type, Accept");
 //*************** */
include('connexion.php');

$data = json_decode(file_get_contents('php://input'), true);
$statement = $pdo->prepare( "INSERT INTO users (firstName, lastName) 
VALUES (:fname, :lname)");
$statement->bindParam('fname', $fname);
$statement->bindParam('lname', $lname);
$result = $statement->execute();
?>

in my post-user file: 在我的后用户文件中:

addUser(fname: string, lname: string) {
if (this.mysqlService.addMysqlUserData(fname, lname)) {
  alert('Data Inserted Successfully');
  this.mysqlService.newDataAdded.emit('yes');
}

} }

and in post-user html file: 并在用户后html文件中:

<div class="form-group row">
<label class="col-sm-2" for="fname">First Name</label>
<div class="col-sm-10">
    <input type="text" class="form-control" id="fname" #fname 
     placeholder="first name">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2" for="lname">Last Name</label>
<div class="col-sm-10">
    <input type="text" class="form-control col-sm-8" id="lname" #lname 
 placeholder="last name">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
    <button class="btn btn-primary" (click)="addUser(fname.value, 
 lname.value)">Add user</button>
</div>
</div>

And it works fine. 而且效果很好。 Thanks a lot for your answers regard gr 非常感谢您的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM