I want to post form data and retrive the same from post method but it fails. It posts nothing to the external link. I have created external link in PHP. What is the problem?
This is the complete code. I'm using HTTP from from '#angular/http'. This is the complete code
my home.html code is bellow
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic3 Server Send Test
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label floating>id</ion-label>
<ion-input type="text" name="id" [(ngModel)]="data.id"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input type="text" name="name" [(ngModel)]="data.name"></ion-input>
</ion-item>
<button ion-button block (click)="submit()">Submit to server</button>
</ion-list>
<ion-card>
<ion-card-header>
Response
</ion-card-header>
<ion-card-content>
<b>{{data.response.id}}</b>
<b>{{data.response.name}}</b>
</ion-card-content>
</ion-card>
</ion-content>
my home.ts code is bellow
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '#angular/http'; //https://stackoverflow.com/questions/43609853/angular-4-and-ionic-3-no-provider-for-http
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
data:any = {};
constructor(public navCtrl: NavController, public http: Http) {
this.data.name = '';
this.data.id = '';
this.data.response = '';
this.http = http;
}
submit() {
var link = 'http://127.0.0.1:3000/passdata';
var myData = JSON.stringify({id: this.data.id, name: this.data.name});
this.http.post(link, myData)
.subscribe(data => {
this.data.response = data["_body"]; //https://stackoverflow.com/questions/39574305/property-body-does-not-exist-on-type-response
}, error => {
console.log("Oooops!");
});
}
}
Can you please try it on chrome browser with developer tool open, and show us the network tab, see if there's any request fail and paste the error in the post.
From your code, I can see you forgot to specify "Content-Type": "application/json" in the request header.
And you probably have to remove this.http = http; from your constructor.
Related
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.
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);
?>
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.
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')
);
}
}
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"));