Angular post to codeigniter return NULL - php

I'm new in Angular, and i'm developing a login auth service, but i'm gettin some troubles to make the post data for an backend developed in CodeIgniter.
I'm sending: username and userpassword, to URL: http://192.168.1.162/advance-managemente_2.1/login
Follow my code:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { UserData } from './login/user.model';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
userData: UserData;
getUserDetails(username, userpassword) {
console.log(username, userpassword);
const userdata = JSON.stringify({user: {login: username, password: userpassword}});
const headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
console.log(userdata);
// post these details to API server return user info if correct.
return this.http.post(`http://192.168.1.162/advance-management_2.0/login`, userdata, {headers: headers, observe: 'response'})
.subscribe(res => {
console.log(res);
},
err => {
console.error(err);
});
}
}
And my console:
Note: my variables with username and userpassword is working.
And in codeigniter's backend project is setted these headers:
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
And the function os codeigniter is:
function login(){
$json = $this->input->post('user');
echo json_encode($json);
}
If you observe, my login function have an ECHO with json_encode of i'm sending to her.
But, in console, the body is returning NULL.
I'd like to know what I might be doing wrong, and how to fix it, because it was for him to return a JSON, but it does not seem to be identifying my POST.
Thanks to anyone who can help,
Have a nice day!

Related

Ionic 3 Uncaught (in promise): [object Object]

I am new to Ionic 3 and mobile development. I am trying to connect a MySQL DB to my Ionic app and a PHP Restful API. I tested the API with Postman and it is working just fine, in order to implement it in Ionic I did the following,
I first made a provider named Authservice:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/api/"
/*
Generated class for the AuthServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on
and Angular DI.
*/
#Injectable()
export class AuthServiceProvider {
constructor(public http: HttpClient) {
console.log('Hello AuthServiceProvider Provider');
}
postData(credentials, type) {
return new Promise((resolve, reject) => {
let headers = new HttpHeaders();
this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers })
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
And a Signup page:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service/auth- service';
/**
* Generated class for the SignupPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage {
responseData: any;
userData = {"username": "","password": "", "name": "","email": ""};
constructor(public navCtrl: NavController, public authServiceProvider: AuthServiceProvider) {
}
signUp() {
this.authServiceProvider.postData(this.userData, "signup").then((result) =>{
this.responseData = result;
console.log(this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
});
}
goToLogin() {
this.navCtrl.pop();
}
}
When running this I am getting an Uncaught (in promise): [object Object] error as can be seen here.
UPDATE
I am now getting the following error:
Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost/PHP-SLIM-RESTFUL/API/signup", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost/PHP-SLIM-RESTFUL/API/signup: 404 Not Found", error: "<html><head><title>404 Page Not Found</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body><h1>404 Page Not Found</h1><p>The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.</p>Visit the Home Page</body></html>" } signup.ts:36:6
postData(credentials, type) {
let headers = new HttpHeaders();
return this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers });
}
this will return observable on the signup page, just subscribe it.
You can make use of Typescript's async methods to make your life easier
Your postData method in async
AuthServiceProvider:
public async postData(credentials, type): Promise<any> {
let headers = new HttpHeaders();
await this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers }).toPromise();
}
Signup page:
public async signUp(): void {
try {
// request successful
this.responseData = await this.authServiceProvider.postData(this.userData, "signup");
console.log(this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
}
catch(e) {
// some error occured, handle it here..
console.log(e);
}
}
Don't forget to import toPromise operator in AuthServiceProvider
import 'rxjs/add/operator/toPromise';
Try importing HttpModule in app.module.ts;
{import HttpModule } from '#angular/http'
Then add HttpModule to the imports;
imports :
[BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
]

Angular 4 POST to php my sql not working

I Am trying to make a simple login check , using angular 4 , php my sql .
Now i am able to send the details to the php , but i am not able to receive the status after it , i have no idea why.
Simply, i want to check if the username and password are correct, then return some json , else , return false result.
Help please.
Angular :
import { Injectable } from '#angular/core';
import { Http, Response ,RequestOptions,Headers} from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
#Injectable()
export class appService {
postResponse:any ;
status;
constructor(private http:Http) { }
insertData() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:80/angularsql/sql.php',JSON.stringify({firstName:'Joe',lastName:'Smith333'}),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:'') => this.postResponse = res);
}
}
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$data = json_decode( file_get_contents('php://input'),true );
$fname = $data['firstName'];
$lname = $data['lastName'];
$con = new mysqli('localhost','root','','angular');
if($fname=='anan' && $lname=='kassis') {
$sql = "insert into users_tbl(firstName,lastName) values('".$fname."','".$lname."')";
$result = $con->query($sql);
$data = [ "status" => "CORRECT" ];
echo json_encode($data);
}
else {
$data = [ "status" => "wrong details inserted" ];
echo json_encode($data);
}
//echo $result;
?>
I think you should change
subscribe((res:'') => this.postResponse = res);
to
subscribe(res: any =>
{
this.postResponse = res);
console.log(res.status)
}
Here, res will be an object and you can console.log(res.status)
Edit: You cannot have the console.log after the subscribe call, because at this stage the http call has not received a response yet.
Other things to consider:
And probably set json type headers in your php response
header('Content-Type: application/json');
Also, you should use parametrized queries (like PDO) when querying your database
I think this line is the issue:
.subscribe((res:'') => this.postResponse = res);
Change your call into:
insertData(): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:80/angularsql/sql.php', JSON.stringify({
firstName: 'Joe',
lastName: 'Smith333'
}), { headers: headers })
.map(res => res.json())
.catch((error: any) => Observable.throw(
{ message: error.json().message, details: error.json().details }));
}
You should subscribe to the insertData() method. And in your .post() you map the result and you catch the errrors (if any).

Angular app not calling a php

So, I have a simple crud Angular web application and for some reason when i try to do an http.post to a php nothing happens. Sorry but i know nothing about web apps and php and i have to deliver this.
Service that contains the call (basically the line that calls the post php is in the update method, but i include all the file because i dont know if there is something wrong elsewhere):
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DbService {
public headers:Headers;
constructor(public http:Http) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
}
getStock(){
return this.http.get('http://localhost/api/stock/read.php').map(res => res.json());
}
getSales(){
return this.http.get('http://localhost/api/ventas/read.php').map(res => res.json());
}
updateDB(member:string){
let data:Data;
data = {name:member};
console.log(data.name);
this.http.post('http://localhost/api/productos/create.php',
JSON.stringify(data),
{
method: 'POST',
headers: this.headers
});
}
}
interface CarrItem{
id: number,
name: string,
price: number,
stock: number,
quantity: number
}
interface Data{
name: string
}
And this is the php, it works when used in a web browser, i knw cause it inserts correctly into the database.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");
header("Accept: application/json;");
require '../config/database.php';
$m_name = "20:23";
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(strlen($m_name)>0){
$insertMember = $pdo->prepare("INSERT INTO member(membershipType, firstName, lastName, sex, birthDate, accumulatedPurchases) values('Dorada', ?, 'M', 'Other', '2018-1-1', 50.0)");
$insertMember->execute(array($m_name));
$otra = $pdo->prepare("INSERT INTO brand(brandName) values('SI')");
$otra->execute();
}
else{
$otra = $pdo->prepare("INSERT INTO brand(brandName) values('NO')");
$otra->execute();
}
Database::disconnect();
?>
First, I think it is working in your browser because you are doing a GET (not a POST) and you are not using any request parameters in your code above. As-is, your code will run into problems getting the request data.
POST-ing JSON data to PHP is a little complex. PHP will not automatically parse the data for you. Instead, you'll have to do something like ...
$jsonEncoded = file_get_contents('php://input');
$jsonDecoded = (array) json_decode($jsonEncoded, true);
INSTEAD OF THAT, MIGHT BE EASIER ... to just let Angular send the data in old-style application/x-www-form-urlencoded format and let PHP auto-parse it into $_POST for you.
let body = new URLSearchParams();
body.set('name', member);
body.set('age', 28);
this.http.post(my_url, body);

Angular2 - Send POST request to server

I'm building a mobile app to display news feed. In my app, one should be able to post a status.
The status will be sent to PHP server using POST method.
Now my problem is PHP cant read the POST request I sent using angular2.
This is my code:
form.html
<form class="sample-form post-form" [formGroup]="post_form" (ngSubmit)="createStatus()">
<ion-item>
<ion-textarea rows="7" placeholder="What's happening?'" formControlName="status"></ion-textarea>
</ion-item>
<section class="form-section">
<button ion-button block class="form-action-button create-post-button" type="submit" [disabled]="!post_form.valid">Post</button>
</section>
</form>
form.ts
import { Component } from '#angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Validators, FormGroup, FormControl } from '#angular/forms';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'form-page',
templateUrl: 'form.html'
})
export class FormLayoutPage {
section: string;
post_form: any;
url: string;
headers: Headers;
constructor(public nav: NavController, public alertCtrl: AlertController, public http: Http) {
this.headers = new Headers();
this.headers.append("Content-Type", "application/x-www-form-urlencoded");
this.section = "post";
this.post_form = new FormGroup({
status: new FormControl('', Validators.required),
});
}
createStatus(){
console.log(this.post_form.value);
this.url = "https://domain.com/mobileREST/poststatus.php";
this.http.post(this.url, this.post_form.value, { headers: this.headers})
.map(res => res.json())
.subscribe(res => {
console.log(res);
},
err => {
console.log(err);
})
}
}
poststatus.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$status = $_POST["status"];
echo json_encode($status);
?>
Firebug Console:
I cant seem to find the error here. Really appreciate your help
I had the same problem. You can't send the POST params like the javascript object. You have to pass it like URLSearchParams. I've made a function which will do it for you. It will loop through the object and make URLSearchParam and return it as string.
private _buildParams(params: any) {
let urlSearchParams = new URLSearchParams();
for(let key in params){
if(params.hasOwnProperty(key)){
urlSearchParams.append(key, params[key]);
}
}
return urlSearchParams.toString();
}
And then you call http post:
this._http.post(this.url, this._buildParams(params), {headers: this.headers});
To get the posted data just add this line in your php file
// get posted data
$data = json_decode(file_get_contents("php://input"));

Delete data in Angular2 app in PHP

How would one delete data from a MySql database using PHP code in an Angular2 application? The closest advice is for Angular 1 and is as follows:
$scope.deleteProduct = function(id){
// ask the user if he is sure to delete the record
if(confirm("Are you sure?")){
// post the id of product to be deleted
$http.post('delete_product.php', {
'id' : id
}).success(function (data, status, headers, config){
// tell the user product was deleted
Materialize.toast(data, 4000);
// refresh the list
$scope.getAll();
});
}
}
Is it possible to use the post method similarly:
import { Injectable } from '#angular/core';
import { Http, Response, Headers } from '#angular/http';
import 'rxjs/Rx';
#Injectable()
export class HttpService {
constructor(private http: Http) {}
deleteData() {
return this.http.post('delete_record.php')
}
}
Any insight/experience with Angular2/PHP would be appreciated.
Yes, the http post works similarly in angular2. Since you want to use post, i guess you also want to add a body to the request.
import { Injectable } from 'angular/core';
import { Http } from 'angular/http';
#Injectable()
export class HttpService {
constructor(private http: Http) {}
deleteData(data: SomeObject) {
let url = "delete_record.php";
let body = JSON.stringify(data);
return this.http.post(url, body)
.subscribe(
result => console.log(result),
error => console.error(error)
);
}
}
You can also send a delete request, which would be "best practice".
return this.http.delete(url)
.subscribe(
result => console.log(result),
error => console.error(error)
});
More about the http-client here https://angular.io/docs/ts/latest/guide/server-communication.html

Categories