Skip to content
Advertisement

Unable to post angular form data using web api

contact.component.html

<form class="contact-form" #f = "ngForm">
    <div class="row">
        <div class="col-md-12">
            <input type="text" name="name" class="input" [(ngModel)] = "selectedContact.name"> 
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <input type="text" name="phone" class="input" [(ngModel)] = "selectedContact.phone">
        </div>
        <div class="col-md-6">
            <input type="text" name="email" class="input" [(ngModel)] = "selectedContact.email"> 
        </div>
        <div class="col-md-12">
            <textarea class="required valid" name="message" [(ngModel)] = "selectedContact.message"></textarea>
            <button class="btn btn-primary" name="submit" type="button" (click)="createOrUpdateContact(f)">Send Message</button>
        </div>
    </div>
</form>

contact.component.ts

import { Component, OnInit } from '@angular/core';
import { Title } from "@angular/platform-browser";
import { ApiService } from '../../api.service';

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

  constructor(private title: Title, private apiService: ApiService) { }

  contacts:  any;
  selectedContact:  any  = {name:null, email:  null, phone: null, message: null};

  ngOnInit(): void {
    this.title.setTitle('Finance | Contact Us');
    this.apiService.readContacts().subscribe((contacts: any)=>{
      this.contacts = contacts;
      console.log(this.contacts);
    })
  }

  createOrUpdateContact(form){
      this.apiService.createContact(form.value).subscribe((contacts: any)=>{
        console.log("Contact created, ", contacts);
      });
  }
}

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Contact } from  './model/contact.model';
import { Observable } from  'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  PHP_API_SERVER = "http://localhost";

  constructor(private httpClient: HttpClient) { }

  readContacts(): Observable<Contact[]>{
    return this.httpClient.get<Contact[]>(`${this.PHP_API_SERVER}/financeAPI/read.php`);
  }

  createContact(contact: Contact): Observable<Contact[]>{
    return this.httpClient.post<Contact[]>(`${this.PHP_API_SERVER}/financeAPI/create.php`, Contact);
  }
}

create.php

<?php
require 'config/db.php';
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
  $request = json_decode($postdata);
  if(trim($request->name) === '' || trim($request->email) === '' || trim($request->phone) === '' || trim($request->message) === '')
  {
    return http_response_code(400);
  }
  $name = mysqli_real_escape_string($con, trim($request->name));
  $email = mysqli_real_escape_string($con, trim($request->email));
  $phone = mysqli_real_escape_string($con, trim($request->phone));
  $message = mysqli_real_escape_string($con, trim($request->message));
  $s_date = date('Y-m-d');
  $sql = "INSERT INTO `contact`(`name`,`email`,`phone`,`message`,`s_date`) VALUES ('{$name}','{$email}','{$phone}','{$message}','{$s_date}')";
  if(mysqli_query($con,$sql))
  {
    http_response_code(201);
    $policy = [
      'name' => $name,
      'email' => $email,
      'phone' => $phone,
      'message' => $message,
      's_date' => $s_date
    ];
    echo json_encode($policy);
  }
  else
  {
    http_response_code(422);
  }
}

I am new in angular and I am simply trying to insert angular form data in mysql using web api. Now, What happen here when I try to read data from database it work perfectly and all data are showing in my console. But when I fill form data then it throw an error as mention below.

POST http://localhost/financeAPI/create.php 400 (Bad Request)

ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: 'Bad Request', url: 'http://localhost/financeAPI/create.php', ok: false, …}

I don’t know why this happen? Please help me to solve this issue.

Thank You

Advertisement

Answer

in your submit button try change

createOrUpdateContact(f)

to

createOrUpdateContact(f.value)

to get the value from your form

<button class="btn btn-primary" name="submit" type="button" (click)="createOrUpdateContact(f.value)">Send Message</button>

I replicate your code Here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement