4

I've been searching for two weeks to find the answer to my question, which I feel should be relatively simple but I haven't been using the right keywords. I know Angular is front-end framework and I can use whatever database and backend I'd like.

For a school project, I am creating an Ionic 3/Angular 4 application with a MySQL database and one of the assignments asks for a login/registration system. While there are many tutorials to do this with Firebase, I haven't seen any revolving around MySQL.

My basic question is, how do I set up my register.ts file to run a PHP file on the server and pass through data like name, username, email, and password? We learned basic PHP in school, though I am open to using Node/Mongo if there's a helpful quickstart - we're not allowed to use any BaaS like Firebase.

Here's some code: register.ts file

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

/**
 * Generated class for the RegisterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

let user_id: any;
let headers = new Headers(
  {
    'Content-Type' : 'application/x-www-form-urlencoded'
  });





@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  @ViewChild('username') username;
  @ViewChild('email') email;
  @ViewChild('firstname') firstname;
  @ViewChild('password') password;
  @ViewChild('confirmpass') confirmpass;
  //successfully gets this data from the form on the HTML register page


  constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController, public http: Http) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
  }

registerUser() {
  //runs this when register button is pressed
  //bad validation, but what can ya do 
  if (this.password.value != this.confirmpass.value) {
    console.log("confirm pass and password don't match");
    let confirm = this.alertCtrl.create({
    title: 'Sorry!',
    message: 'Password & Confirm Password do not match',
    buttons: [
        {
          text: 'Okay',
          handler: () => {
            console.log('Disagree clicked');
          }
        }
      ]
    });
    confirm.present();
  } else {
//this is where I'm struggling
  let url: string = 'mySchoolsDB.com/myuser/insertuser.php';
  let responseData: any;
  let userData = {"firstname": this.firstname.value, "username": this.username.value, "password": this.password.value, "email": this.email.value };
    console.log('would register user with', this.username.value, this.password.value);

   console.log(userData);
    this.http.post(url, userData, {headers:headers, method:"POST"})
    .map(res => res.json())
    .subscribe(
        data => {
          console.log(data);
        },
        err => {
          console.log("ERROR!: ", err);
        }
    );
  }
}



}

insertuser.php

<?php

header('Access-Control-Allow-Origin: *');

$servername = "db.school.edu";
$dbusername = "myuser";
$dbpassword = "mypass";
$dbname = "mydbname";


$firstname = $_POST['firstname'];
$password = $_POST['password'];
$username = $_POST['username'];
$email = $_POST['email'];
// Create connection
$conn = mysqli_connect($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} 

$sql = "INSERT INTO users (firstname, email, username, password)
VALUES ('$firstname', '$email', '$username', '$password')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error:  " . $sql . "<br>" . mysqli_error($conn);
} 

mysqli_close($conn);
?>

1 Answer 1

2

Here are the two lines that you need to change

First change :

let headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded'});

to :

let headers = new Headers({'Content-Type': 'application/json'});

Second

Change

this.http.post(url, userData, {headers:headers, method:"POST"})

To :

this.http.post(url, userData, {headers}).map(...)....
Sign up to request clarification or add additional context in comments.

2 Comments

Hi there Vivek. Thanks for your response - that solved one problem but of course another came up: gyazo.com/8b4cd4938659748c08fb2865b3f22a62.png
Use cross browsing tools.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.