Origin http://localhost:xxxx is not allowed by Access-Control-Allow-Origin - php

I'm trying to fetch some data from my mySQL DB stored on 000webhost, and Ionic show me that error message:
I've read that I need to enable CORS policy, but don't understand on where I should.
That's the fetch_data.php code:
<?php
require 'config.php';
$query = "SELECT lat, lng FROM gps WHERE id = (SELECT MAX(ID) FROM gps)";
$result = mysqli_query($con, $query);
if($result === FALSE) {
printf("Error: %s\n", mysqli_error($con));
}
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array(“lat”=>$row[0],“lng”=>$row[1]));
}
echo json_encode(array($response));
?>

add to index.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');

Related

Simple Rest API Account creation

I am trying to build Simple Rest api for my php website but i am having issue on creating the account
create.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers,
Authorization, X-Requested-With");
include_once 'database.php';
include_once 'data.php';
$database = new Database();
$db = $database->getConnection();
$item = new emmanuel_api($db);
$item->user_name = $_GET['user_name'];
$item->user_pass = $_GET['user_pass'];
$item->user_email = $_GET['user_email'];
$item->full_name = $_GET['full_name'];
if($item->createUsers()){
echo 'Account created successfully.';
} else{
echo 'Account could not be created.';
}
?>
I think i am getting error on my Create.php please help me to resolve this issue
Also how i can convert this user_pass into MD5
Thanks

Getting a http_response_code(404) when trying to pass a record id dynamically in phpmyadmin. Am trying to integrate MySQL on-pre with Salesforce

I am trying to update one particular record or row corresponding to a id passed dynamically. There is a record belonging to that id. When I give the URL followed with the "?id=3", I am getting a 404 error, saying no such record exists. Would like to know what error I have done. The following is my code.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/database.php';
include_once '../objects/constitute.php';
$database = new Database();
$db = $database->getConnection();
$constitute = new Constitute($db);
$data = json_decode(file_get_contents("php://input"));
$constitute->id = isset($_GET['id']) ? $_GET['id'] : die();
$constitute->name = $data->name;
$constitute->address = $data->address;
$constitute->constitution_type = $data->constitution_type;
$constitute->organisation_id = $data->organisation_id;
if($constitute->update()){
http_response_code(200);
echo json_encode(array("message" => "Constitute was updated."));
}
else{
http_response_code(503);
echo json_encode(array("message" => "Unable to update constitute."));
}
?>
The following is the update() method:
function update(){
$query = "UPDATE
" . $this->table_name . "
SET
name = :name,
address = :address,
constitution_type = :constitution_type,
organisation_id = :organisation_id
WHERE
id = ?";
$stmt = $this->conn->prepare($query);
$this->id=htmlspecialchars(strip_tags($this->id));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->constitution_type=htmlspecialchars(strip_tags($this->constitution_type));
$this->organisation_id=htmlspecialchars(strip_tags($this->organisation_id));
$stmt->bindParam(':id', $this->id);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':address', $this->address);
$stmt->bindParam(':constitution_type', $this->constitution_type);
$stmt->bindParam(':organisation_id', $this->organisation_id);
if($stmt->execute()){
return true;
}
return false;
}
Also when i try to pass the updated record in postman, I am getting success code. But the record does not get saved.
Please let me know where I have done mistakes.

Angular 6/PHP Http failure during parsing for

I am currently learning angular 6 and have problems with my connection to the database.
addData(nachname: any, vorname: any, telefon: any) {
return this.client.post('http://localhost/api/add.php', {
nachname,
vorname,
telefon
}).subscribe((data) => {
console.log(data);
});
}
<?php
header("Access-Control-Allow-Credentials: true");
header('Content-type: application/json');
header("Access-Control-Allow-Origin: ".((isset($_SERVER['HTTP_ORIGIN'])) ?
$_SERVER['HTTP_ORIGIN'] : "*"));
header('Access-Control-Allow-Headers: X-Requested-With, content-type,
access-control-allow-origin, access-control-allow-methods, access-control-
allow-headers');
$db = mysqli_connect("localhost", "root", "", "telefonauskunft");
if(!$db){
exit("Verbindungsfehler: ".mysqli_connect_error());
}
$db -> set_charset('utf8');
$model = json_decode(file_get_contents("php://input"));
$sql = "Insert Into telefonauskunft ('Nachname', 'Vorname', 'Telefon')
Values ('$model -> Nachname', '$model -> Vorname', '$model ->
Telefon');";
if($model->Nachname){
$qry = $db->query($sql);
}
$db->close();
?>
These are my codes. I got a normal select query with this.client.get (...).
Unfortunately I get with this code
error
:
{error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…,
Http failure during parsing for
Where is my problem? I thank you in advance for answers and help
You should print something out in your PHP file, for instance a boolean value stating that the database query was successful. Ideally, you should follow common JSON API guidelines, cf. http://jsonapi.org/format/upcoming/
print json_encode($db->query($sql));

How to delete record from table using Angular http.delete with PHP backend?

I am trying to delete a record from the database table using Angular on frontend and PHP on the backend. I am passing the id through URL and trying to get it back with $_GET['id'] but it doesn't work (no error in console).
PHP API:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require_once("includes/initialize.php");
$db = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase) or die('Could not connect to database');
$data = json_decode(file_get_contents("php://input"));
$id;
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
// update the ECD
if(ECD::deleteECD($id)){
echo '{';
echo '"message": "The center was deleted."';
echo '}';
}
// if unable to update the ECD, tell the user
else{
echo '{';
echo '"message": "Unable to delete the center."';
echo '}';
}
And Angular http.delete:
deleteCenter (id: number): Observable<{}> {
const url = `${this.D_ROOT_URL}${id}`;
return this.http.delete(url);
}
I tested the URL to make sure it's passing the correct URL.
The delete() method returns a cold observable, which means that the HTTP request is not sent until someone subscribes to the observable. You should write this:
return this.http.delete(url).subscribe();

Getting Blank record for this code

Look at this code, i am getting empty record in database.
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
this line not giving first name but it gives blank value not the value that i am trying to insert into the database.
whats wrong in this code?
create.php
<?php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
$lastname=isset($_POST['lastname'])?mysql_real_escape_string($_POST['lastname']):"";
$email=isset($_POST['email'])?mysql_real_escape_string($_POST['email']):"";
$password=isset($_POST['password'])?mysql_real_escape_string($_POST['password']):"";
$status=0;
$query = "INSERT INTO users (firstname,lastname,email,password,status) VALUES ('$firstname','$lastname','$email','$password','$status')";
$insert = mysql_query($query);
if($insert)
{
$data=array("result"=>1,"message"=>"successfully added!");
}
else
{
$data=array("result"=>0,"message"=>"Error!");
}
}
else
{
$data=array("result"=>0,"message"=>"Request Method is Wrong!");
}
mysql_close($conn);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data);
?>
confi.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('tuts_rest', $conn);
?>
Add the following lines in your php file and remove header access you have already added
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
{
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

Categories