Use a php Web serice on Angular Project - php

i've a problem using a php page that execute query on a DB.
The php page is this:
$Query = $_POST['Query'];
// Create connection
$conn = new mysqli($servername, $username, $password,$db);
$result = mysqli_query($conn, $Query);
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode(['result' => $emparray]);
mysqli_close($conn);
My Angular request page:
export class RegisterComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
confirmRegisterClick(username: string, password: string, phoneNumber: string, email: string) {
this.http.post<any>(MYPHPPAGE, new HttpParams().append(QueryNameService, "Select Count(*) As Count From User Where Username='" + username + "'")).subscribe(data => {
console.log(data);
});
});
}
}
This return a json with the result of the query. The problem is that if i execute the call to the php page from postman or from the browser it works well. If i call it from Angular i get this error:
Access to XMLHttpRequest at 'https://www. .... /TestCOR.php' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've tried a lot of online solution anyone work.
I've tried to make a simple php page like that:
<?php
header('Access-Control-Allow-Origin: *');
echo "You have CORS!";
?>
but i always get the same error
Solution Tried:
1:
Add this line to the php page
header('Access-Control-Allow-Origin: *');
2:
Add this lines to the http request header
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT',
'Authorization': 'Bearer szdp79a2kz4wh4frjzuqu4sz6qeth8m3',
});
3:
Use a proxy (i don't know if i did it well, i'm noob to Angular)
"/WEBSITEPATH": {
"target": "http:\\localhost:4200",
"secure": false,
"changeOrigin": true
}
And add this line inside angular.json:
"proxyConfig": "proxy.conf.json"

Related

Vuejs get request from PHP/MySQL doesn't work

I am writing code to get data from MySQL database and using Vuejs,
this.$http.get("api.php?action=read")
.then(response => {
console.log(response);
}, error => {
console.log(error);
});
this request returns all api.php content and doesn't return the data.
here is the api.php file
<?php
require_once('include/config.php');
$res = (['error' => false]);
$action = 'read';
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
if($action == 'read') {
$images = array();
$query = 'SELECT * FROM images ORDER BY id DESC';
$select_images = mysqli_query($connection, $query);
while($image = mysqli_fetch_assoc($select_images)) {
array_push($images, $image);
}
echo json_encode($images);
}
mysqli_close($connection);
header("Content-type: application/json");
echo json_encode($images);
die();
?>
Can anyone help me, Please?
It works,
I added
header("Access-Control-Allow-Origin: *");
to the API file
and make the get request from the localhost/vuejs link,
not like localhost:8080
and it's work
Thanks
Include the header in the php. Note: should be the 1st line before you return anything.
<?php
header("Access-Control-Allow-Origin: *");
And try to run the php code 1st using command prompt:
php -S localhost:8888 ajaxfile.php
Note: try to use different port number as for me it is unable to get the api from same 8080 port in which my vueProject is running.
This will create an api end point with your php. Which will listen to http://localhost:8888/projectname/api.php.
Now When used axios.get(http://localhost:8888/projectname/api.php) will get the response for the api.I havent tried without axios module but i guess it should work.
allRecords: function(){
axios.get('http://localhost:8888/VueAxios/ajaxfile.php').then(response => {
this.users = response.data
console.log(response.data)
})
.catch(function (error) {
console.log(error);
});
}
This function worked for me. Note: axios is a very handy in this situation. Hope it helps.
Try response.body to get the response data:
this.$http.get("api.php?action=read")
.then(response => {
console.log(response.body);
}, error => {
console.log(error);
});

CORS Error when requesting PHP resource from Angular 4 App

I am trying to perform a HTTP Post from my Angular 4 ASP.NET app to another domain I own with a PHP script. However, I am getting some console errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://{MYWEBSITE}/misc/jsondbinsert.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Error: Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }
The PHP script in question is:
<?php
header('Access-Control-Allow-Origin: *'); // allow Cross-Origin-Resource-Sharing (CORS)
header('Access-Control-Allow-Methods: GET, POST');
$link = sqlsrv_connect("SQLSERVER",
array("Database"=>"DATABASE", "UID"=>"SoLegendary", "PWD"=>"PASSWORD"));
if (!$link)
{
die('Could not connect: ' . print_r(sqlsrv_errors()));
}
// retrieve data from post request (JSON form)
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$username = $request->username;
$message = $request->message;
// insert all data into table
$query = "INSERT INTO accounts (username, message)";
$query .= "VALUES ('{$username}', '{$message}')";
mysqli_query($link, $query);
echo "Thanks, {$username}, your message has been saved!<br><br>";
sqlsrv_close($link)
?>
And my angular function sending the request is:
url: string = 'http://MYWEBSITE/misc/jsondbinsert.php';
testbody: any = { "username": "johnsmith123", "message": "hello world!" };
httpPostTest()
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(this.url, JSON.stringify(this.testbody), options)
.subscribe(
(data) =>
{
console.log('Got some data from backend: ', data);
},
(error) =>
{
console.log('Error: ', error);
})
}
Most other CORS questions and guides simply say to add the header(...) line to the top of the PHP script, but that hasn't changed anything for me.
Add header("Access-Control-Allow-Headers: X-Requested-With"); to your php script

Ionic 2 giving wrong response while making post request with php and mysql

I'm doing login from an app using php and mysql. When I put the URL on the browser with credentials appended with it, if the credentials are valid, it prints correct response like success:true. If credentials are not valid, it prints success:false. But when I put do ionic serve and do a login from the app, it prints success:true on console all the time, even if the credentials are not valid.
This is my IONIC-2 code:
var headers = new Headers();
headers.append("Accept",'application/json');
headers.append('Content-Type','application/json');
let options = new RequestOptions({headers:headers});
let postParams={
username: logincreds.username,
password: logincreds.password,
}
this.http.post("http://vaishalishaadi.com/AppLogin.php", postParams, options)
.subscribe(data=>{
console.log(postParams);
console.log(data);
/*if(data.json().success=="success"){
}
else{
} */
}, error => {
console.log(error);
});
Following code is of PHP:
header('Content-type: application/json');
if($check){
session_start();
$_SESSION['u_id'] = $check->u_id;
$_SESSION['u_name'] = $check->u_firstname;
$login_response=["success"=>"true"];
//print(json_encode($login_response));
//echo $check->u_id;
$data[] = array(
'pram'=$username
'id' => $check->u_id,
'fname' => $check->u_firstname,
'lname' => $check->u_lastname,
);
$result = "{'success':true, 'data':" . json_encode($data) . "}";
}
else{
$result = "{'success':false}";
}
echo($result);
Found Solution Over It
Just changed the way I was passing parameters and also removed 'options' argument from post request.
let params = new URLSearchParams();
params.append('username',logincreds.username);
params.append('password',logincreds.password);
this.http.post(url, params)
.subscribe(data=>{
console.log(postParams);
console.log(data);
/*if(data.json().success=="success"){
}
else{
} */
}, error => {
console.log(error);
})
Use URLSearchParams instead of using array to collect parameters being passed to server

How to read JSON response produced by PHP using angular 2

I am using angular 2 as front end and PHP, MySQL for my back end.
PHP properly creates json data but angular 2 unable to read the file content. I am getting the below error.
XMLHttpRequest cannot load http://localhost:81/login.json.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
JSON file available at http://localhost:81/login.json location. I am using XAMPP to run my php file.
My angular 2 code is below.
import { Component, OnInit, Input } from '#angular/core';
import { Http, Response } from '#angular/http';
#Component({
moduleId: module.id,
selector: 'app-header-modal',
templateUrl: './header-modal.component.html',
styleUrls: ['./header-modal.component.css']
})
export class HeaderModalComponent implements OnInit {
private data;
constructor(private http:Http){
}
ngOnInit(){
}
ngAfterViewInit() {
this.getData();
}
getData(){
this.http.get('http://localhost:81/login.json')
.subscribe(res => this.data = res.json());
console.log('User Data: '+this.data);
}
}
My PHP code is below.
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");
include 'connect.php';
$username = str_replace(" ", "", $_POST['username']);
$password = str_replace(" ", "", $_POST['password']);
$query = mysql_query("select username, password, id from registration where username='".$username."' and password='".$password."'");
$result = mysql_fetch_array($query);
if($result){
$data = array(
array('userId' => $result['id'],'userName' => $result['username'])
);
$fp = fopen('login.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
?>
<script>
history.go(-1);
</script>
<?php
}
?>
Can somebody help!
This appears to be a CORS issue with the php server backend you are trying to use. You angular App doesn't have the ability to make a request to the php server because of CORS.
Once you have properly configured the php server the request should start working.
More information on CORS.

How to post json object with Http.post (Angular 2) (php server side)

I'm trying to recreate Post JSON from angular 2 to php but it doesn't work as there's nothing in the $_REQUEST variable on php side
The code:
searchHttp({body}: any): Promise<any>
{
let headers = new Headers ({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, method: "post" });
let test_this = {"search": "person"};
return this.http.post(this.post_url, JSON.stringify(test_this), options)
.toPromise()
.then(response =>
{
return response.text();
})
.catch(this.handleError);
}
Is there something I'm missing? I know that posts works with another format because I have that answered in another question.
Also, is http.request better than http.post?
Edit:
After much consultation with Angular/Javascript experts, they believe this is a php issue. So anyone with knowledge of how to accept JSON objects on php side will be gladly welcomed.
angular 2 client side part
ngOnInit() {
let body=Api+'product.php'+'?id=' + this.link_id;
this._callservice.callregister(body)
.subscribe( data => {
this.outputs=data;
},
error => console.log("Error HTTP Post"),
() => console.log("completed") );
}
}
call.service.ts
import {Injectable} from '#angular/core';
import {Router} from '#angular/router';
import {Http, Response, Headers, RequestOptions} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Injectable()
export class AuthenticationService {
constructor(private _http:Http){}
postregister(api:any){
// console.log(api);
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, method: "post"});
return this._http.get(api,options)
.map(res => res.json())
.catch(this.handleError);
}
private handleError (error: Response) {
console.error(error);
return Observable.throw(error.json().error || ' error');
}
}
Server side PHP
make sure on server side you have these three lines in php code.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
Php file:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$servername = "localhost";
$username1 = "root";
$password = "root";
$dbname = "product";
$e=array("error"=>1,"message"=>"Account Already Exists");
$accountCreated = array( "error" =>0,
"data" => array(
"username" => "amit" ,
"password" => "anypassword",
"role"=> "user",
"id" => "anyid" ) );
// Create connection
$conn = mysqli_connect($servername, $username1, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = $_GET["username"];
$Pass = $_GET["password"];
$role= $_GET["role"];
$sql="SELECT COUNT(*) as user FROM users WHERE username = '$username'";
$result = mysqli_query($conn,$sql);
$line = mysqli_fetch_assoc($result);
$count = $line['user'];
if($count!=0)
{
echo json_encode($e);
}
else
{
$sql="INSERT INTO users(username,password,role)VALUES('$username','$Pass','$role')";
$result=mysqli_query($conn,$sql);
$sql="select * from users where username ='$username'";
$result=mysqli_query($conn,$sql);
$line=mysqli_fetch_assoc($result);
{
$accountCreated['data']['username']=$line['username'];
$accountCreated['data']['password']=$line['password'];
$accountCreated['data']['role']=$line['role'];
$accountCreated['data']['id']=$line['id'];
}
echo json_encode($accountCreated);
}
?>
i hope this will work for you .. for json i guess you should pass as options and use json decode for values you get in options.
There doesn't appear to be anything wrong with the Angular code. The issue is in what the PHP is expecting to receive. I am not a PHP expert, but as you've mentioned that it works fine with jQuery, then that indicates that your PHP is expecting a URL-encoded value (as jQuery tends to work with that), not a JSON value.
In other words, what the server is trying to parse is:
search=person
What you are sending is:
{ "search": "person" }
Try something more like the following to send it in the format you're wanting:
let test_this = { "search": "person" };
let headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: "post" });
http.post(this.post_url, test_this, options)

Categories