Unable to send data on my database cant understand what is happening - php

Getting this error
Code:
Post_providers.ts
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PostProviders {
server: string = "http://localhost/server_api/"
constructor(public http: Http){
}
postData(body, file){
let type = "application/json; charset=UTF-8";
let headers = new Headers ({'Content-type': type});
let options = new RequestOptions({headers: headers});
return this.http.post(this.server + file, JSON.stringify(body), options)
.map(res => res.json());
}
}
file_aksi.php
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PostProviders {
server: string = "http://localhost/server_api/"
constructor(public http: Http){
}
postData(body, file){
let type = "application/json; charset=UTF-8";
let headers = new Headers ({'Content-type': type});
let options = new RequestOptions({headers: headers});
return this.http.post(this.server + file, JSON.stringify(body), options)
.map(res => res.json());
}
}
config.php
define('Db_name', 'ionic_app');
define('Db_user', 'root');
define('Db_password', '');
define('Db_host', 'localhost');
$mysqli = new mysqli(Db_name, Db_host, Db_password, Db_user);
i have am still trying to solve this issue but still no luck. i am working to solve this error from last 2 days and don't understand that what is the thing which is not correctly done by me.
Error as written in comment by Farrukh iftikhar:
core.js:1448 ERROR SyntaxError:
Unexpected token d in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.js:1091)
at MapSubscriber.project (post_providers.ts:20)
at MapSubscriber._next (map.js:79)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.js:1591)
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (core.js:4740)
at t.invokeTask (polyfills.js:3) at r.runTask (polyfills.js:3)

Related

How to send the "body" parameter to HttpClient.get ()?

I have an "api rest" that I created in PHP, the service returns a JSON with the parameters of "header", "body", "get", "pos", which comes to receive without any type of validation.
Now I have created a service in angular to connect with the "api rest", all right up there, the problem I have is that I want to send a parameter as a "BODY", but I do not know how, I have been investigating but I have not found a shape.
Is it possible to send the "body" via HttpClient.get()?
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ServicioService {
constructor(private http: HttpClient) { }
getQuery(query: string){
const url = `http://localhost:8080/servicio/`;
const headers = new HttpHeaders({
'Authorization': 'Bearer BQAiaibx-we0RSlZFN29B5TPF4t6egxbuuEsc5ZYZhpamHUhImd5'
});
const params = new HttpParams()
.set('page', '2')
.append('page', '3')
.set('sort', 'abc');
return this.http.get (url, { params, headers});
}
getNewReleases(){
return this.getQuery("")
.pipe( map((data: any) => {
return data;
}));
}
}
A GET request does not have a body.
You should use POST or PUT.
You can read here a little bit about the http methods.
About the GET: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect
So, it would be wrong to send a body because a GET method should not change anything.

passing a parameter from Angular 7 to a PHP API

I need to know how to pass parameters between angular 7 and a PHP API
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('http://localhost/backend/json/data_products.php');
}
getProduct(productId) {
const params = new HttpParams().set('id', productId);
return this.http.get('http://localhost/backend/json/data_product.php/', {params});
}
}
but I got this error
core.js:12584 ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK
Please refer to Angular doc: https://angular.io/api/common/http/HttpClient#get
get(url: string, options: { headers?: HttpHeaders | { [header:
string]: string | string[]; }; observe?: "body"; params?: Ht...)
It should be like:
this.http.get('http://localhost/backend/json/data_product.php/', { params: params });
in your case.
I think you need to pass header in request like below.May be this is help you.
update(id: number, data: any){
let model = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.put( 'http://localhost/backend/json/data_product.php/'+id,model, options);
}

binding response string to object in ionic 3 using php and angular 5

I am new to ionic 3 and I can retrieve data in response _body as string format but i can't able to bind key and values.
Here list.ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { Injectable } from "#angular/core";
import { Http } from '#angular/http';
import { HttpClientModule } from '#angular/common/http';
import 'rxjs/add/operator/map';
import { HomePage } from '../home/home';
/**
* Generated class for the ListCustomerPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-list-customer',
templateUrl: 'list-customer.html',
})
export class ListCustomerPage {
data:any = {};
items:any = {};
public res_data: any ='';
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
this.http = http;
this.res_data= this.navParams.get('res_data');
}
ionViewDidLoad() {
var link='http://localhost/CustomerRegistration/src/php/list.php?id='+this.res_data;
this.http.get(link).subscribe(
data =>{
this.items=data._body;
});
}
}
In console output:
Response {_body: "[{"customer_id":"440","customer_name":"test","cust…ated_at":"2018-08-17 07:55:07","deleted_at":"0"}]", status: 200, ok: true, statusText: "OK", headers: Headers, …}
In list.html page
i get error key value "customer_name" undefine.
<h3>customer name</h3><b>{{items.customer_name }}</b>
how to use response data in list.html
As per response data is in JSON format you need to parse JSON data like below.
this.items = JSON.parse(data);
or in your case, your data is in one step inner with key-value "body".
So use like this :
let jsonResponse = JSON.parse(data);
this.items = data("_body");
this will help you to get data in an array format.

Angular 4 HttpClient Cannot sent data with POST

Angular 4.4.4
This is my app component
constructor(
private http: HttpClient,
)
this.http.post('/api.php', {name, age}).subscribe(data => {
console.log(data);
});
api.php -> exit(json_encode($_POST));
Don't receive any data in $_POST
return [];
(let xmlRequest = new XMLHttpRequest();
....
works fine)
I try set header
let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8');
not work
Sorry for this question but I spent 1 day and still could not find solution.
ps. client and server has same origin.
You need to put your parameters into a FormData Object on the Angular side.
const params = new FormData();
params.append('para1', 'value1');
params.append('para2', 'value1');
this.http.post('/api.php', params).subscribe(....)
Now you can get the parameters on the PHP part of your project with $_POST['para1'] and $_POST['para2'].
I like this solution more than getting all the stuff with file_get_contents, as it looks more straight forward for me.
please try I hope it will help you
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class LandingService {
private apiUrl = 'http://localhost:5000/';
list:any;
headers : any;
constructor(private _http: HttpClient){
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
}
getsearchResponse(searchText){
this.list ={"sentences":searchText}
return this._http.post(this.apiUrl+'searchBotsNew',this.list,this.headers)
.map(res =>res.json())
.do(data => console.log(JSON.stringify(data)));
}
}
I found the solution to this.
In PHP, $_POST only accept formdata.
With request header 'Content-Type: application/json' you can receive it with file_get_contents('php://input');
So
$_POST = json_decode(file_get_contents('php://input'));

SyntaxError: Unexpected token < in JSON at position 0 in Ionic2 App

I register the data to the database.Then I want to list the data but I get an error(SyntaxError: Unexpected token < in JSON at position 0).I do not understand where I'm making mistakes.
list.html
<ion-header>
<ion-navbar>
<ion-title>list</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let isim of dataisim">{{isim}}</ion-item>
</ion-list>
</ion-content>
list.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {ServiceProvider} from "../../providers/datamember";
import { Http, Headers, Response, ResponseOptions } from '#angular/http';
#IonicPage()
#Component({
selector: 'page-list',
templateUrl: 'list.html',
})
export class ListPage {
dataisim : any;
constructor(public navCtrl: NavController, public navParams:
NavParams,public service:ServiceProvider,
public http : Http) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ListPage');
this.service.getList().subscribe(data =>
this.dataisim = data );
console.log(this.dataisim);
}
}
service.ts
import { Injectable } from '#angular/core';
import { Http, Headers, Response, ResponseOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Storage } from '#ionic/storage';
#Injectable()
export class ServiceProvider {
public local : Storage;
mydata : any;
api : string = 'http://localhost:8080/ionic2_kaydet.php';
api2 : string = 'http://localhost:8080/kaydet3.php';
url : string = "http://localhost:8080/listele.php";
constructor(public http: Http) {
}
postLogin(data){
console.log("api data:" + data);
let headers = new Headers({ 'Content-Type' : 'application/x-www-form-
urlencoded' });
return this.http.post(this.api, data, {
headers:headers,
method:"POST",
}).map(
(res:Response) => {return res.json();}
);
}
getList() {
let headers = new Headers({ 'Content-Type' : 'application/x-www-form-
urlencoded' });
return this.http.get(this.url, {
headers:headers,
method:"GET",
}).map(
(res:Response) => {return res.json();}
)
}
}
listele.php
<?php
header("Access-Control-Allow-Origin: *");
$conn = new mysqli("localhost", "root", "", "ionic2");
$data= array();
$select = "select * from user2";
$qr = $conn->query($select);
while($row = $qr->fetch_assoc()){
$data[]=$row;
}
print json_encode($data);
?>

Categories