简体   繁体   中英

Http.post form data from angular2+ to php

I've spent hours searching SO for this, but I wasn't able to find anyone who was trying to do what I was. I'm trying to use http.post to send (an array of) data from an HTML form through Angular to PHP. When I try to do this, it sends the hardcoded values in the PHP file to PostgreSQL fine, but I'm not sure if Angular is sending the data to PHP or if I'm not accessing the $_POST variable correctly.

This is the code I have for this right now:

register-form.component.html:

<div class="container">
  <h1>Sign Up</h1>
  <h5>Items marked with a * are required.</h5> <br>
  <form (ngSubmit)="onSubmit(model)" #registerForm="ngForm">
    <div class="form-group">
      <label for="username">Username *</label>
      <input type="text" class="form-control width" id="username" required [(ngModel)]="model.username" name="account[username]"
                                                                                                    #username = "ngModel">
      <div [hidden]="username.valid || username.untouched" class="alert alert-danger">
        Username is required
      </div>
    </div>
    <div class="form-group">
      <label for="password">Password *</label>
      <input type="text" class="form-control width" id="password" minlength="6" required [(ngModel)]="model.password"
                                                                              name="account[password]" #password = "ngModel">
      <div [hidden]="password.valid || password.untouched" class="alert alert-danger">
        Password is required and must be at least 6 characters
      </div>
    </div>
    <div class="form-group">
      <label for="email">E-mail *</label>
      <input type="text" class="form-control width" id="email" required [(ngModel)]="model.email" name="account[email]"
                                                                                              #email = "ngModel" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">
      <div [hidden]="!email.hasError('pattern') || email.untouched" class="alert alert-danger">
        E-mail is required and must be a valid e-mail
      </div>
    </div>
    <div class="form-group">
      <label for="phoneNumber">Phone Number</label>
      <input type="text" pattern="[0-9]*" class="form-control width" minlength="10" maxlength="10" id="phoneNumber"
                                            name="account[phone]" [(ngModel)]="model.phoneNumber" #number = "ngModel">
      <div [hidden]="number.pristine">
        <div [hidden]="!number.hasError('minlength')" class="alert alert-danger">Phone number should only have 10 digits in xxxxxxxxxx format.</div>
        <div [hidden]="!number.hasError('pattern')" class="alert alert-danger">Phone number should only have digits.</div>
      </div>
    </div>
    <input type="submit" class="btn btn-success"[disabled]="!registerForm.form.valid" value="Submit">
  </form>
</div>

register-form.component.ts:

import { Component, OnInit } from '@angular/core';
import { user } from '../user';
import { Http, HttpModule, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-register-form',
  templateUrl: './register-form.component.html',
  styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent implements OnInit {

  constructor(private http: Http) { }

  model = new user('','','','');

  ngOnInit() { }

  submitted = false;

  onSubmit(...event: user[]) {
    this.submitted = true;
    console.log(event); //just for testing - outputs inputted data from form into console
    console.log(event[0]); //same as above
    var test = this.http.post('http://localhost/register-form-component.php', event[0]); //should this just be 'event'?
    test.subscribe();
  }

}

register-form-component.php:

<?php
    $dbconn = pg_connect("host=localhost port=5432 dbname=sample user=sample password=sample");
    if(!$dbconn) {
      echo "connection failed";
      exit;
    }
    $test = ["testuser","testpass132","example@gmail.com",1234566543];
    $values = [$_POST['username'], $_POST['password'], $_POST['email'], $_POST['phoneNumber']];
    $result = pg_prepare($dbconn, "insert_accounts", 'INSERT INTO accounts (username, password, email, phone_number) VALUES ($1,$2,$3,$4)');
    $result = pg_execute($dbconn, "insert_accounts", $test); //this works
    $result = pg_execute($dbconn, "insert_accounts", $values); //the data table in PGAdmin skips a primary key every time this file runs; it is because of this line (see edit below).
    if (!$result) {
        echo "An INSERT query error occurred.\n";
        exit;
    }
    pg_close($dbconn);
?>

Thanks!

EDIT : This wasn't showing up before, but when I open up localhost/register-form-component.php, it gives the following output:

Array
Warning: pg_execute(): Query failed: ERROR: null value in column "username" violates not-null constraint DETAIL: Failing row contains (31, null, null, null, null). in /Library/WebServer/Documents/register-form-component.php on line 16
An INSERT query error occurred.

I assume this means that $_POST contains [null, null, null, null]. This same error shows up when event[0] is changed to event in the http.post().

EDIT 2 : First output is of console.log(event), second is of console.log(event[0])

EDIT 3 : This is what shows up in the network tag after submitting the form

EDIT 4 : In the header tab under network, it shows this.

It turns out that the reason why PHP was showing $_POST as containing null values is because it was empty, as I had not declared what was to be in it. Using the method in Mike Brant's answer , I added the following lines to my code:

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

And it worked! Thank you Jaime for patiently abiding by all of my questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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