I've got a problem I can't seem to solve. I want to return my given input with a PHP file. This gives me the following error:
"↵Notice:
Trying to get property of non-object in
C:\xampp\htdocs\script.php on line SOMEWHERE↵null"
This is the code:
import {Component} from '#angular/core';
import {Http, Response} from '#angular/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: Http) {
}
cityName = 'From an Input field';
searchCity() {
this.http.post(
'http://localhost/directory/map/script.php', this.cityName)
.subscribe((data) => {
console.log('This is wat I get returned: ', data);
}, (error) => {
console.log('Errorrror::: ', error);
}
)
}
}
And of course my php file:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Type: application/json');
$data = json_decode(file_get_contents("php://input"));
$cityName = $data->cityName;
echo json_encode($cityName);
?>
The function searchCity() gets triggered with a button.
Replace below line:
$cityName = $data->cityName;
With this
$cityName = isset($data->cityName) ? $data->cityName : "";
Related
Client given below Ajax Post call, when i will open below PHP api file in browser then the static data is inserting correctly, now i am trying using Angular, but I am not able to understand how to convert this below call into component.ts and service
<?php
//creating payload parameters:
$classTitle = 'Demo Class on 3rd April, 2020';
$classInfo = 'This is a demo class scheduled to understand API';
$classDateTime = '2020-11-12 11:30 AM';
$timezone = 'Asia/Kolkata';
$classDuration = 15;
$classRecording = 'yes';
$classAutoStart = false;
$recordingAutoStart = false;
$classVideoRes = 720;
/*xyz.com*/
$apiKey = '12345';
$secretKey = '12345';
// Create token header as a JSON string
$header = json_encode(['alg' => 'HS256','typ' => 'JWT']); // ensure to place first alg part and next typ part
// Create token payload as a JSON string
$payload = json_encode(['classTitle' => $classTitle ,'classInfo' => $classInfo ,'classDateTime' => $classDateTime ,'timezone' => $timezone ,'classDuration' => $classDuration ,'classRecording' => $classRecording ,'classAutoStart' => $classAutoStart ,'recordingAutoStart' => $recordingAutoStart ,'classVideoRes' => $classVideoRes ,'apiKey' => $apiKey]);
// Encode Header to Base64Url String
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
// Create Signature Hash
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secretKey , true);
// Encode Signature to Base64Url String
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
// creating JWT token variable
$jwt_token = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
// creating authorization varibale
$authorization = 'Bearer '.$jwt_token;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax
({
type: "POST",
url: 'https://xyz/client/schedule',
contentType: 'application/json',
data: JSON.stringify({
"apiKey": "12345"
}),
dataType : 'json',
headers: {
'authorization': '<?php echo $authorization; ?>'
},
success: function(retval)
{
// alert(retval);
console.log(retval);
// var success = retval.success;
}
});
</script>
I have updated Question and added after two replied answer
Below is my model class
export class Schedule1 {
classTitle: string;
classInfo: string;
classDateTime: string;
timezone: string;
classDuration: number;
classRecording:string;
classAutoStart: boolean;
recordingAutoStart: boolean;
classVideoRes: number;
constructor() {
}
}
Below is component.ts on button click passing static values
import { Schedule1 } from '../Models/Schedule1.model'
Schedule1: Schedule1 = new Schedule1();
addSchedule(scheduleForm: NgForm): void {
//static data parameter passing
this.Schedule1.classTitle='hi Class on 3rd April, 2020';
this.Schedule1.classInfo= 'This is a demo class scheduled to understand API';
this.Schedule1.classDateTime= '2020-11-12 11:30 AM';
this.Schedule1.timezone= 'Asia/Kolkata';
this.Schedule1.classDuration= 15;
this.Schedule1.classRecording= 'yes';
this.Schedule1.classAutoStart= false;
this.Schedule1.recordingAutoStart= false;
this.Schedule1.classVideoRes= 720;
//const data = JSON.stringify(this.Schedule1);
const data = {
apiKey: "dcbf187d-bdfe-431b-8f60-fa19bf51cd85",
data: JSON.stringify(this.Schedule1)
}
this.subscription = this.userSvc
.fetchData("https: //xyz.com/client/schedule", data)
.subscribe(
data => {
// Data on Success
console.log("data", data);
},
error => {
console.log("error", error);
}
);
}
Below is service.ts
fetchData(url: string, data: any): Observable<any> {
const headers = {
Authorization: "Bearer "+"1234",
"My-Custom-Header": "foobar",
contentType: "application/json"
};
return this.http.post(url, data, {
headers
});
}
in console getting this error.
Parsing HTTP request is pretty simple in Angular. Below are the steps you need to follow:
Step 1:
import the HttpClientModule in your app module like this:
import { HttpClientModule } from '#angular/common/http';
imports: [ HttpClientModule ]
Step 2:
Create a service for your application where you will store all the HTTP request calls.
NOTE: This part is not necessary as you can do HTTP calls directly in your component but for best practice and good structure this should be followed
So for this step, import HttpClient either in your service (if you have created) or in your component and then do like this below:
import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) { }
createExamCategory(data) {
return this.http.post<{ message: string }>(this.url + '/category/create_exam', data);
}
Let me explain the createExamCategory() method.
The parameter data is the value that is coming from your HTML or any source. And this data will be passed in POST request.
The next line is as I am explaining with service I have just returned the call and will subscribe to it in the component.
The <{ message: string }> is the response that I am getting from the API request. If you are not sure what response you are getting you can just keep it as <any> and Angular will decide the type of response.
Then in the post method (this method is coming from HttpClient declared above) we have 2 pass to parameters by default & the third parameter which is HttpHeader is optional. The 2 parameters are:
URL OF the API.
The request body data for the POST request.
So that's all from the calling side now coming to the subscription part:
If you are directly writing the above part in component then continue with .subscribe(). Now for the service part:
Step 1:
Import the service:
import { SampleService } from 'sample.service';
constructor(private service: SampleService) { }
// Do the call where it is required. I am doing in a normal method
httpMethod() {
this.service.createExamCategory(data).subscribe(response => {
console.log(response); // This is the API response
});
}
Interceptor
import { HttpInterceptor, HttpErrorResponse, HttpEvent, HttpRequest, HttpHandler } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { catchError } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { Router } from '#angular/router';
import { Service } from 'service.service';
#Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router, private service: Service) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (sessionStorage.getItem('token')) {
const cloned = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + sessionStorage.getItem('token'))
});
return next.handle(cloned).pipe(
catchError((err, caught: Observable<HttpEvent<any>>) => {
if (err instanceof HttpErrorResponse && (err.status == 401))
{
this.adminAuthService.clearAuthData();
this.router.navigate(['required route path']);
alert('Session Timeout !! Login Again');
return of(err as any);
}
throw err;
})
);
}
return next.handle(req);
}
}
Here what I have done is while login/authentication I have stored the generated JWT token by the backend service in session and validated if the API url is valid or not.
After doing this in app.module.ts specify the interceptor in the providers like this:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
Hoping this will help you 🙂
create a service like below.
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { Observable } from "rxjs";
#Injectable({
providedIn: "root"
})
export class ScheduleDataService {
constructor(private _http: HttpClient) {}
fetchData(url: string, data: any): Observable<any> {
const headers = {
Authorization: "Bearer my-token",
"My-Custom-Header": "foobar",
contentType: "application/json"
};
return this._http.post(url, data, {
headers
});
}
}
then you can call this service in your component like below.
import { Component, OnDestroy, OnInit, VERSION } from "#angular/core";
import { ScheduleDataService } from "./schedule-data.service.ts";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit, OnDestroy {
name = "Angular " + VERSION.major;
private subscription;
constructor(private _scheduleDataService: ScheduleDataService) {}
ngOnInit() {
this.subscription = this._scheduleDataService
.fetchData("https://xyz/client/schedule", {
apiKey: "myapikey"
})
.subscribe(
data => {
// Data on Success
console.log("data", data);
},
error => {
console.log("error", error);
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Let me know if you have any doubt.
You can Create service Like and call in component.
services.ts
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: "root"
})
export class UserService{
constructor(public http: HttpClient){}
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': ''
});
public getData(url: string, data: any): Observable<any> {
return this.http.post(url, data, { headers: headers});
}
}
components.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from './services.ts';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class Components implements OnInit {
constructor(public userService: UserService){}
public ngOnInit(): void {
const data = { apiKey: "myapikey" }
this.userService.getData(url, data).subscribe((res)=>{
code...
})
}
}
I want to delete my item using 'srno' in my angular project. I have passed the 'srno' to the URL but it shows some error.
I checked my PHP code using postman, It is successfully worked.
I can't recognize my .ts file syntax error.
Error :
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost/angular_crud/delete.php?srno=srno", ok: false, …}
delete.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl } from '#angular/forms';
import { HttpClient, HttpParams } from '#angular/common/http';
import { ActivatedRoute } from '#angular/router';
interface Delete{
srno: String;
}
#Component({
selector: 'app-delete',
templateUrl: './delete.component.html',
styleUrls: ['./delete.component.css']
})
export class DeleteComponent implements OnInit {
delete: Delete[] = [];
srno : String;
myControl1 = new FormControl();
constructor(private http: HttpClient, public route: ActivatedRoute) { }
ngOnInit() {
}
personDelete(){
this.srno = this.myControl1.value;
var url = "http://localhost/angular_crud/delete.php?srno=srno";
this.http.get<Delete[]>(url).subscribe(data => {
this.delete = data;
console.log(data);
})
}
}
This is the delete.component.html
<h1 style="text-align: center">Adding Items here!</h1>
<div>
<p>
<mat-form-field appearance="outline" class="form_field">
<mat-label>Serial Number</mat-label>
<input [formControl]="myControl1" matInput placeholder="Enter the Serial number">
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
<mat-hint>ie : 787</mat-hint>
</mat-form-field>
</p>
</div>
<button (click)="personDelete()" mat-raised-button color="warn" class="btn">Delete</button>
This is the delete.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,DELETE');
header("Access-Control-Allow-Header: H-Requested-With");
$con = mysqli_connect("localhost","root", "", "savedata");
$srno = $_GET["srno"];
if($con->connect_error){
die("Connection failed: " . $con->connect_error);
}
$sql = "DELETE FROM savedata WHERE srno='$srno'";
if($con->query($sql) === TRUE){
echo "Record delete successfully";
}
else{
echo "Error deleting record: ". $con->error;
}
$con->close();
?>
Your API doesn't return JSON. Try
this.http
.get(url, {responseType: 'text'})
.subscribe(data => {
console.log(data);
});
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.
Here is my problem with my backend which is MySQL. One query is giving me this set of data
{"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz","parti":"Babbleopia","departement":"Sweden","commune":"Täby"}]
A array of arrays , and I wanna access to the nested arrays for my Angular project. I mean this part
[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz","parti":"Babbleopia","departement":"Sweden","commune":"Täby"}]
Here is my component
import { IPaeComponent } from './paeI';
import { NgModel } from '#angular/forms/src/directives';
import { Component, OnInit } from '#angular/core';
import { CandidatService } from './paeServices';
#Component({
selector : 'pae-app',
moduleId : module.id,
templateUrl : 'pae1.html'
})
export class PaeComponent implements IPaeComponent{
prog1 : string ="Programme d'Appui aux Elections";
progName1 : string ="Enquête sur les candidats";
searchbar : string ='';
progEl1 : string ="Listes des candidats ciblés";
candInfo : any [];
filter : string;
candidats : IPaeComponent;
errorMessage : string;
constructor (private _candidatService : CandidatService){
}
ngOnInit(): void {
this._candidatService.getCandidatInfo()
.subscribe(candidats => this.candInfo = candidats,
error => this.errorMessage = <any>error);
}
}
My services:
import { IPaeComponent } from './paeI';
import { Injectable } from '#angular/core';
import { Http, Response , Headers, RequestOptions} from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/do'
import 'rxjs/add/operator/catch'
#Injectable()
export class CandidatService {
private _candidatUrl ='http://localhost/CRUD/api.php/candidat?transform=1';
constructor(private _http : Http){
}
///////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//////////////////////CRUD///////////////////////////
////////////////////////////////////////////////////
///////////////////////////////////////////////////
getCandidatInfo() : Observable<IPaeComponent[]>{
return this._http.get(this._candidatUrl)
.map((response : Response)=><IPaeComponent[]> response.json())
.do(data => console.log('All '+ JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error : Response){
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
addCandidatInfo (body: Object): Observable<IPaeComponent[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this._http.post(this._candidatUrl, body, options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
updateCandidatInfo (body: Object): Observable<IPaeComponent[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this._http.put(`${this._candidatUrl}/${body['id']}`, body, options) // ...using put request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
removeInfo (id:string): Observable<IPaeComponent[]> {
return this._http.delete(`${this._candidatUrl}/${id}`) // ...using put request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
}
And what it looks like when I debug in my browser:
Thanks in advance for your help
Just extract the array from your response:
getCandidatInfo() : Observable<IPaeComponent[]>{
return this._http.get(this._candidatUrl)
.map((response : Response)=><IPaeComponent[]> response.json().candidat) // here
.do(data => console.log('All '+ JSON.stringify(data)))
.catch(this.handleError);
Try this
this._candidatService.getCandidatInfo()
.subscribe(candidats => {
this.candInfo = candidats.candidat;
// if you want get value from particular index
cosnole.log(this.candInfo[0]);
// Or you can iterate loop to get each value
},
error => this.errorMessage = <any>error);
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"));