Unable to post data from form to mysql in Angular 2 - php

I am able to fetch the value I add in my textbox in a variable in my addoperation.ts file, but I am unable to send it to my database.
Here is my addoperation.ts code:
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Headers, Http, HttpModule ,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-operationadd',
templateUrl: './operationadd.component.html',
styleUrls: ['./operationadd.component.css']
})
export class OperationaddComponent implements OnInit {
name="abc";
constructor(private http: Http) { }
ngOnInit() {
}
submitdata(){
console.log("Data Submitted");
console.log(this.name);
this.http.post('http://example.com/adv8/prod-api/crudtable-add.php', {name: this.name})
.map((res:Response) => res.json())
.subscribe(result =>{ });
}
}
and this is my addoperation.html
<form>
<div class="form-group">
<label for="name">First Name:</label>
<input type="text" class="form-control" #fname [(ngModel)]="name" name="firstname">
</div>
<button type="submit" class="btn btn-default" (click)="submitdata()">Submit</button>
</form>
My API is working fine, I have tested it on Chrome Postman. I pass a variable name: jess in the body and I get a SUCCESS message, but I am unable to save it from Angular.

After a lot of search i am able to post the data in my db, below I am pasting code , should be useful to someone in future.
Note: adding headers is important.
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Headers, Http, HttpModule ,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-operationadd',
templateUrl: './operationadd.component.html',
styleUrls: ['./operationadd.component.css']
})
export class OperationaddComponent implements OnInit {
name="abc";
constructor(private http: Http) { }
ngOnInit() {
}
submitdata(){
console.log("Data Submitted");
console.log(this.name);
var body = "name=" + this.name;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://example.com/adv8/prod-api/crudtable-add.php', body, {
headers: headers
})
.map(res => res.json())
.subscribe(
// data => this.saveJwt(data.id_token),
// err => this.logError(err),
() => console.log('Authentication Complete')
);
}
}

Related

Data don't load at the first time

I'm developing an Ionic app with angular. It has an API with php. So, I've a service that returns a JSON, the thing is, that the first time it loads the page, it doesn't load the data from the JSON.
The service:
import { Injectable } from '#angular/core';
import { HttpClient, HttpClientModule } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class PlayerService {
posts;
baseURL: String;
constructor(public http: HttpClient) {
this.baseURL = 'http://127.0.0.1:8000/'
}
getPlayers() {
this.http.get(this.baseURL + 'GetPlayers')
.subscribe(data => {
this.posts = data;
});
return this.posts;
}
How I load it:
#Component({
selector: 'app-players',
templateUrl: './players.page.html',
styleUrls: ['./players.page.scss'],
})
export class PlayersPage implements OnInit {
constructor(private playerService: PlayerService) { }
players = this.playerService.getPlayers();
ngOnInit() {
}
}
HTML:
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Players</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let p of players">
<ion-label>
<h2>{{p.name}}</h2>
<h3>{{p.mail}}</h3>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
You should be returning the observable on your component, instead of the service. This will ensure the data is loaded upon initialisation of the component.
#Component({
selector: 'app-players',
templateUrl: './players.page.html',
styleUrls: ['./players.page.scss'],
})
export class PlayersPage implements OnInit {
constructor(private playerService: PlayerService) { }
ngOnInit() {
this.playerService.getPlayers().subscribe(data => {
this.players = data;
});
}
}
And on your service.ts, make the following changes.
getPlayers() {
return this.http.get(this.baseURL + 'GetPlayers');
}
Do try to understand the purpose of services, and components. As stated on the Angular documentation,
Ideally, a component's job is to enable the user experience and
nothing more. A component should present properties and methods for
data binding, in order to mediate between the view (rendered by the
template) and the application logic (which often includes some notion
of a model).
On the other hand, the duty of fetching and saving data (carrying out of HTTP requests) should be delegated to services.

angular 8 elements disappearing after post request

I'm a beginner in angular , i was trying to establish a connection with database using php as backend programming language , it was working fine and the elements were showing from database but when i inserted them to the database , it does work and they are inserted to the database but my elements disappear when the form is submitted and when the form is submitted again they flash for seconds .
MY HTML CODE
<form (submit)="loginUser($event)">
<input type="text" placeholder="User name" id="name" >
<input type="password" placeholder="password" id="pass">
<button type="submit" >Log in</button>
{{name}}
</form>
<ul *ngFor="let item of datas ">
<li>{{item.name}} {{item.pass}}</li>
</ul>
MY LOGIN.COMPONENT FILE
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { iEmployee } from '../../empolyee';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor( private Auth:AuthService) { }
public datas;
ngOnInit() {
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
loginUser(event: { preventDefault: () => void; target: any; }){
event.preventDefault();
const target = event.target;
const name=target.querySelector('#name').value;
const pass=target.querySelector('#pass').value;
this.Auth.createuser(name,pass).subscribe(data=>this.datas=data);
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
}
MY AUTH.SERVICE FILE
import { Injectable } from '#angular/core';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { iEmployee } from '../empolyee';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http:HttpClient) { }
private url : string='http://localhost:81/example/Angular/php/display.php';
private url2:string='http://localhost:81/example/Angular/php/addNew.php';
getUserDetail() {
return this.http.get(this.url)
}
createuser(name , pass) {
return this.http.post(this.url2,{name,pass},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
}
}
MY ADDNEW.PHP FILE
<?php
header('Access-Control-Allow-Origin: *');
include 'connection.php';
$data = json_decode(file_get_contents("php://input"),true);
$name= $data['name'];
$pass= $data['pass'];
$sql="insert into test(name,pass) values ('$name','$pass')";
$result = mysqli_query($con, $sql);
?>

Ionic image upload with PHP server

I have a problem with my ionic app.
I want to upload an image to my php server when i click on a button but it seems that i am doing something wrong...
Communication.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic3 Server Send Test
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<button ion-button (click)="uploadFile()">Upload</button>
</ion-item>
</ion-list>
</ion-content>
Communication.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '#angular/common/http';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '#ionic-native/file-transfer';
#Component({
selector: 'communication',
templateUrl: 'communication.html'
})
export class CommunicationPage {
imageURI:any;
imageFileName:any;
constructor(public navCtrl: NavController,
private transfer: FileTransfer) {}
uploadFile() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'ionicfile',
fileName: 'ionicfile',
chunkedMode: false,
headers: {}
}
fileTransfer.upload('C:/Users/Nathan/Desktop/Recognize/src/pages/communication/test.png', 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
}
}
I have this error when i click on the upload button :
FileTransferError {code: 1, source:"C:/Users/Nathan/Desktop/Recognize/src/pages/communication/test.png", target: "http://someserver", http_status: null, body: null, …}
I know there is a problem with the url of the "test.png" file because of code 1 error.
Do you have any idea ?
You need to add image targetPath in fileTransfer.upload() like this,
var targetPath = this.file.dataDirectory + imgName;
fileTransfer.upload(targetPath, 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
Hey Nathan the problem you are having is because of the URL of file, here you are giving the url only test.png.
Rather than you should use FileChooser plugin for cordova which gives the absolute URL of the file.
import { FileChooser } from '#ionic-native/file-chooser';
constructor(private fileChooser: FileChooser) { }
function() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'ionicfile',
fileName: 'ionicfile',
chunkedMode: false,
headers: {}
}
this.fileChooser.open()
.then(uri => {
fileTransfer.upload(uri, 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
})
.catch(e => console.log(e));
}
Comment down if you want some more help.

Angular - how to get variable from local PHP file

I want to get variable from my getData.php file that is in src/assets folder of angular project.
<?php
...
echo json_encode('test');
?>
get-data.service :
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
#Injectable()
export class GetDataService {
constructor(private http: Http) {}
getTest(): Observable<any> {
return this.http.get('assets/getData.php')
.map(response => response.json());
}
}
app.component :
import { Component } from '#angular/core';
import { GetDataService } from './services/get-data.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private getDataService: GetDataService) { }
title = 'Run Chart Generator';
data;
getTestTwo() {
this.getDataService.getTest()
.subscribe(data => {
this.data = data;
console.log(this.data)
});
}
}
When I call function getTestTwo I've got:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
When I change php from echo json_encode('test') to echo 'test' and service from .map(response => response.json()) to .map(response => response) then I've got in console:
Object { _body: "<?php include('simple_html_dom.ph…", status: 200, ok: true, statusText: "OK", headers: Object, type: 2, url: "http://localhost:4200/assets/getDat…" }
How can I retrieve a variable from my php file?
#angular/cli: 1.4.1
#angular/core: 4.3.6
Your PHP file won't work under a NodeJS project.
You need to separate your Angular App from your server logic. Use Nginx or Apache to serve your PHP file, then you will be able to call it in your getTest() function.

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"));

Categories