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

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

Related

Bad connection from ionic 3 app to php server (export and import mysql)

I would like to know if this kind of error is because i have something wrong on my code (ts in ionic 3 app) or is for some issue in remote server:
[app-scripts] [14:05:12] console.error: API Error : 404
[app-scripts] [14:05:12] console.error: API Error : {"_body":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta
[app-scripts] charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST
[app-scripts] /sited.com/test/exportar.php</pre>\n</body>\n</html>\n","status":404,"ok":false,"statusText":"Not
[app-scripts] Found","headers":{"content-security-policy":["default-src
[app-scripts] 'self'"],"x-content-type-options":["nosniff"],"connection":["keep-alive"],"x-powered-by":["Express"],"content-length":["170"],"date":["Thu","
[app-scripts] 21 Mar 2019 17:05:12 GMT"],"content-type":["text/html;
[app-scripts] charset=utf-8"]},"type":2,"url":"http://localhost:8100/sited.com/test/exportar.php"}
I've tried to debug with
ionic cordova run android --device -l -c
My ts/ionic code is like this:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
///
import { AlertController } from 'ionic-angular';
import { Http, Headers, Response, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
let user_id: any;
let headers = new Headers({'Content-Type': 'application/json'});
//'Content-Type' : 'application/x-www-form-urlencoded'
#IonicPage()
#Component({
selector: 'page-exportar',
templateUrl: 'exportar.html',
})
export class ExportarPage {
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ExportarPage');
let url: string = 'sited.com/test/exportar.php';
let responseData: any;
//let userData = {"nombre":"juan" };
// console.log(userData);
this.http.post(url,{
nombre: 'juan'
}, {headers})
//this.http.post(url, userData, {headers:headers, method:"POST"})
.map(res => res.json())
.subscribe(
data => {
console.log(data);
},
err => {
console.error('API Error : ', err.status);
console.error('API Error : ', JSON.stringify(err));
}
);
}
}
and my php looks like this one:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: content-type, authorization");
header('Access-Control-Max-Age: 86400');
$servername = "localhost";
$dbusername = "xxxx";
$dbpassword = "x";
$dbname = "xxx";
$nombre = $_POST['nombre'];
// Create connection
$conn = mysqli_connect($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO cristian (nombre) VALUES ('$nombre')";
echo($sql);
if (mysqli_query($conn, $sql)) {
echo "ok";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Thanks in advance for some expert help or tip!!

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

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)

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.

Invalid Request type Angular2

Can you tell me where I'm wrong? When I use the Postman then it's working.But why I cannot do the same using Angular2? Here the backend api is from PHP.I have never used PHP backend before.Is that different than normal ASP.net Web Api? I mean the way we have to send the parameters and all...
Service.ts
import { Injectable } from '#angular/core';
import { Http, RequestOptions, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class AuthenticationData {
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login";
constructor(public http: Http) {
}
//to login
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
/*let body = {
username: username,
password: password,
}*/ Not working this too :(
let body='username=myname&password=admin';//I tried hardcode value.But not working
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
login.ts
//to login
loginUser(): void {
if (this.loginForm.valid) {
this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password).subscribe(
data => {
this.response = data;
},
err => {
console.log(err);
},
() => console.log('Complete')
);
}
}
Error:
body: "{"error":"Invalid Request type","status":"201"}", status: 200,
ok: true, statusText: "OK",
Php:
<?php
class ControllerApiLogin extends Controller {
private $error = array();
public function index() {
$json = array();
if (($this->request->server['REQUEST_METHOD'] == 'POST') && !empty($this->request->get['username']) && !empty($this->request->get['password'])) {
if(!empty($this->request->get['username']) && !empty($this->request->get['password'])){
$this->load->language('common/login');
$this->document->setTitle($this->language->get('heading_title'));
// User
$this->registry->set('user', new Cart\User($this->registry));
if ($this->validate()) {
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
if($token_count==0)
{
$this->session->data['token'] = $token;
}else{
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
$this->session->data['token'] = $token;
}
$this->load->model('user/user');
$user_info = $this->model_user_user->getUserByEmail($this->request->get['username']);
$tokeninfo = array();
if(count($user_info) > 0){
$tokeninfo = array(
'token' => $token,
'user_id' => $user_info['user_id'],
'ip' => $this->request->server['REMOTE_ADDR']
);
$date_expired = $this->model_user_user->addUserapitoken($tokeninfo);
}else{
$date_expired = '';
}
$json['token'] = $token;
$json['date_expired'] = $date_expired;
$json['status'] = '200';
}else{
$json['error'] = "No match for Username and/or Password.";
$json['status'] = '201';
}
}else{
$json['error'] = 'Something Went Wrong!!! <br> PLease Enter Correct Login Credentials!!!';
$json['status'] = '201';
}
//$this->response->addHeader('Content-Type: application/json');
//$this->response->setOutput(json_encode($json));
}
else{
$json['error'] = 'Invalid Request type';
$json['status'] = '201';
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->addHeader('HTTP/1.1'.$json['status']);
$this->response->setOutput(json_encode($json));
}
protected function validate() {
//$this->registry->set('user', new Cart\User($this->registry));
if (!isset($this->request->get['username']) || !isset($this->request->get['password']) || !$this->user->login($this->request->get['username'], html_entity_decode($this->request->get['password'], ENT_QUOTES, 'UTF-8'))) {
$this->error['warning'] = $this->language->get('error_login');
}
return !$this->error;
}
}
OP's feedback: I have to use it like this.Cheers :)
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login&username=";
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
let body = '';
let options = new RequestOptions({ headers: headers });
let url = this.authenticationEndPoint + encodeURI(username) + '&password=' + encodeURI(password);
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleError);
}
Original Answer:
headers.append('content-type', 'application/json');
let body='username=myname&password=admin';//I tried hardcode value.But not working
You seem to be setting content type as json. So your body needs to be set as an object. Do:
let body ={
username:myname,
password:admin
}
And then send the request. It should convert this to json and send.
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
Seems like you want to use URLSearchParams instead, and send the data as x-www-form-urlencoded instead of JSON. The URLSearchParams will encode the parameters as you have tried when hardcoding, but I think your problem is when you are trying to send it as JSON, send it as x-www-form-urlencoded instead. So try this:
import { URLSearchParams } from '#angular/http';
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('username',username);
body.set('password',password)
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body.toString(), options)
.map(this.extractData)
.catch(this.handleError);
}
//you need to import this
import { Http, Headers, URLSearchParams, Request, RequestOptions, RequestMethod } from '#angular/http';
this.body= {
"username":myname,
"password":admin
} //body is defined here
let headers = new Headers();
headers.append('HeaderKey', headerValue);
let options = new RequestOptions({
method: RequestMethod.Post,
url: this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password),
body: this.body,
headers: headers
});
//here you are making request
this.http.request(new Request(options))
.map(res => res.json())
.subscribe(data => {
//data is fetched
if(data.code==200){
this.response = data;
}
else{
console.log("some issue with the api response")}
}, err => {
console.log("ERROR!: ", err);
});
May be this way things will work for you

Categories