1

I am creating an app with Angular 9 and Ionic 5 and I am very new at this so forgive me if I missed something obvious. The following is my App code:

import { HttpClient } from '@angular/common/http';
etc...

constructor(private http: HttpClient) { }

  authenticate(phone: string, password: string) {
    let frmData = new URLSearchParams();
    // let frmData = new FormData(); //just to show that I have tried this also
    const headeroptions = {
      // 'enctype': 'multipart/form-frmData;', // when using FormData above
      'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    };
    frmData.append('emailOrMobile', phone);
    frmData.append('password', password);
    console.log("login: " + phone + " " + password); //this shows the values correctly
    console.log("frmData: " + frmData); //frmData: emailOrMobile=1234567890&password=111111
    return this.http.post<any>('https://example.com/APP/login.php', {frmData}, {headers: headeroptions}
      // {"emailOrMobile":phone, "password":password} //Also tried without creating the object beforehand
    ).subscribe(data => {
      console.log("Subscribed Data: ");
      console.log(data);
    },
      error => {
            console.log('error: ' + error.error);
            console.log('Name: ' + error.name);
            console.log('Message: ' + error.message);
            console.log('Status: ' + error.status);
          });
  }

I have also tried other versions where I have replaced .subscribe... etc. with:

.pipe(tap(this.setUserData.bind(this)));

but that hasn't worked either. There are a lot of solutions out there, but most deal with older versions of Angular and do not use HttpClient or they do and suggest subscribing to the observable - which I am already doing.

At the other end, the php code is straightforward:

$data = json_decode(file_get_contents("php://input"), true);

If I echo or try to use $data, it is an empty array that prints as {} or just a blank space (can't get it consistently to print '{}'). I even tried

count($data);

and that returns 0.

2
  • Have you tried passing the arg to the http.post() as frmData instead of{frmData}? Commented Sep 22, 2020 at 10:36
  • Thanx, just tried that - didn't make any difference. Commented Sep 22, 2020 at 11:17

1 Answer 1

1

I have made a test here in my local machine and it worked passing the args as a javascript object:

{ emailOrMobile: phone, password: password}

In the php script in the backend I usually allow CORS requests. I am not sure if you do need in your environment (see the command header("Access-Control-Allow-Origin: *");).

The full typescript of the page:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
    
  
  constructor(private http: HttpClient) {
    this.authenticate('123', 'mypassword');
  }

  authenticate(phone: string, password: string) {
    const headeroptions = {
      'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    };
  
    let params =  { emailOrMobile: phone, password: password};
    return this.http.post<any>('http://localhost/backend/authtest.php', params, {headers: headeroptions}).subscribe(data => {
      console.log("Subscribed Data: ");
      console.log(data);
    },
    error => {
      console.log('error: ' + error.error);
      console.log('Name: ' + error.name);
      console.log('Message: ' + error.message);
      console.log('Status: ' + error.status);
    }); 
  }
}

The php script in the backend authtest.php:

<?php
    //Allow requests from different domain:
    header("Access-Control-Allow-Origin: *");

    $data = json_decode(file_get_contents("php://input"), true);
    
    echo json_encode([ 'success' => true, 'params' => $data]);
    

The output I got in Chrome after runing the ionic application:

enter image description here

Sign up to request clarification or add additional context in comments.

8 Comments

Already tried that, see the line: "// {"emailOrMobile":phone, "password":password} //Also tried without creating the object beforehand" (sorry, I mistyped phone instead of emailOrMobile in my original post)
I have tested that code here and that code worked for me. I will edit my answer to include the php code I have used in the backend as well
instead of count($data), what is the output of print_r($data); in the php script?
just edited my answer including the full files and the chrome printscreen, maybe it helps you track the error in your env.
I save the value of $data and count($data) in a MySQL database - since I can't really see the output from the api. Meanwhile, I used your php code (the last line - everyting else I already had) and I get: params: {…} ​​ frmdata: [] ​​​ length: 0 ​​​ <prototype>: Array []
|

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.