How can use AngularJs $stateChangeSuccess to populate data to MySQL using PHP? - php

I have this funcion who list objects with arrays:
//onload event-- to set the values
$scope.$on('$stateChangeSuccess', function () {
$scope.cart=sharedCartService.cart;
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
});
I need get all datas and insert all (populate) in a database. I´m using MySQL and PHP.
Thanks.

You create a file let say its called save.php
In that file you will have something like
header("Access-Control-Allow-Origin: *");
Global $db;
$db = new PDO('mysql:dbname=databasename;host=localhost', 'dbuser', 'dbpassword');
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);
}
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$cart = $request->cart;
$total_qty = $request->total_qty;
$total_amount = $request->total_amount;
}
else {
echo "Not called properly!";
}
$query = $db->prepare("
INSERT INTO yourtable
(cart, total_qty, total_amount)
VALUES
(:cart, :total_qty, :total_amount)");
$query->execute(array(
':cart' => $cart,
':total_qty' => $total_qty,
':total_amount' => $total_amount));
And in your function in Angular (stateChangeSuccess) you make a post request on for example http://localhost:8080/save.php
$http.post(url, data, config)
.then(
function(response){
// success callback
},
function(response){
// failure callback
}
);

Related

How to prepare $_POST in PHP with Redux Toolkit Query [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 8 months ago.
I am trying to experiment with Redux Toolkit Query mutations.
What I have now at the front-end:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
export const postApi = createApi({
reducerPath: "postApi",
baseQuery: fetchBaseQuery({
baseUrl: "https://webcodingcenter.com/shared/",
prepareHeaders: (headers, { getState }) => {
headers.set("Content-Type", "application/json");
return headers;
}
}),
endpoints: (builder) => ({
getPost: builder.query({
query: (id) => `get_post.php?id=${id}` // expects a JSON response
}),
updatePost: builder.mutation({ // <-- attention here
query: (body) => {
console.log(123, body);
return {
url: `update_post.php`,
method: "POST",
body
};
}
})
})
});
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetPostQuery, useUpdatePostMutation } = postApi;
And the back end (update_post.php):
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
die();
}
$str="HELLO WORLD";
$r="";
for ($i = 0; $i < strlen($str); $i++){
if (rand(0,100)>50) $r .= strtoupper($str[$i]);
else $r .= strtolower($str[$i]);
}
file_put_contents("data".$_POST["id"].".txt",$r);
echo json_encode($_POST);
//echo json_encode(array("post"=>$r));
?>
As you can see from the Code Sandbox here, $_POST is always empty. How can I pass the data to $_POST?
This solves it:
$data = json_decode(file_get_contents('php://input'), true);

PHP not getting data sent by post from React in Development, whereas Postman works

Given the following code:
fetch(mockproxy+myphp.php,{
method: 'POST',
headers:{'Token':token["token"]},
body: name,
}).then((response) => response.json())
.then((json)=>{
toast.success(JSON.stringify(json));
})
.catch((err) => {
toast.error(JSON.stringify(err));
})
}
mockproxy is helping bypass CORSS. The file looks like this:
const corsAnywhere = require('cors-anywhere');
const express = require('express');
const apicache = require('apicache');
const expressHttpProxy = require('express-http-proxy');
const CORS_PROXY_PORT = 5000;
// Create CORS Anywhere server
corsAnywhere.createServer({}).listen(CORS_PROXY_PORT, () => {
console.log(
`Internal CORS Anywhere server started at port ${CORS_PROXY_PORT}`
);
});
// Create express Cache server
let app = express();
// Register cache middleware for GET and OPTIONS verbs
app.get('/*', cacheMiddleware());
app.options('/*', cacheMiddleware());
// Proxy to CORS server when request misses cache
app.use(expressHttpProxy(`localhost:${CORS_PROXY_PORT}`));
const APP_PORT = process.env.PORT || 5080;
app.listen(APP_PORT, () => {
console.log(`External CORS cache server started at port ${APP_PORT}`);
});
/**
* Construct the caching middleware
*/
function cacheMiddleware() {
const cacheOptions = {
statusCodes: { include: [200] },
defaultDuration: 60000,
appendKey: (req, res) => req.method
};
let cacheMiddleware = apicache.options(cacheOptions).middleware();
return cacheMiddleware;
}
And the server is a shared server where I upload the PHP files so they can access to the DB. The php receives the data and give a response when I use postman but not when I execute the fetch from the dev website, I'm using react, I think it doesn't matter in this case.
The PHP file:
<?php
$headers = apache_request_headers();
header("Access-Control-Allow-Origin: *, ");
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
exit;
}
if (isset($_POST["name"])) {
echo json_encode(" name" . $_POST["name"]); //returned on postman
}else{
echo json_encode("no name"); //returned on development.
}
exit;
So this is a code i use when i want to fetch all data from a form. You can obviously not loop through all forms like i do below but just your single form.
// Query all forms in the DOM or a specific one if you want
const forms = document.querySelectorAll('form');
// Loop through them
forms.forEach((form) => {
// if method is post
if (form.method === 'post') {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// prepare the data
let data = new FormData(form);
// fetch using the form's
fetch(form.action, {
method: 'post',
body: data,
})
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
// if not post (get really)
} else {
form.addEventListener('submit', (event) => {
// prevent default submit
event.preventDefault();
// build the URL query params from the submitted data
const data = new URLSearchParams(new FormData(form).entries());
// Fetch, URL is formed from the action, append ? and then the query params
fetch(form.action + '?' + data)
// get the text() from the Response object
.then(response => response.text())
.then(text => {
// Display it in the result div
document.getElementById('result').innerHTML = text;
})
}, false);
}
});

Angular cross origin issue in API call Backend PHP?

Facing CORS in angular, when i was trying to make a API call between my localhost to another domain.I am getting 404 issue .
1.Front End : Angualr 7
Front end request part:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods':'POST',
'Access-Control-Allow-Headers': 'Content-Type'
})
}
login(username: string, password: string) {
return this.http.post<any>('http://remote/djaxtesting/enter_uiupgrade/index.php/api/v1/user/validate',
{acc_type: "ADMIN", uemail: "djax_admin#dreamajax.com", upw: "123456"},httpOptions)
.pipe(map(user => {}))
}
Back end coding :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
public function validate_post()
{
$role = array('ADVERTISER','TRAFFICKER','ADMIN','MANAGER');
if($this->post('acc_type') !='' and in_array($this->post('acc_type'),$role))
{
switch(strtoupper($this->post('acc_type')))
{
case "ADMIN":
$adminObj = $this->do_networks->validate_user($this->post('uemail'),$this->post('upw'),$this->post('acc_type'));
//$this->response($adminObj, 200);
}
}
}
enter image description here
We using php for api. Helping handing needs to solve this issue ?
The problem with the option method. Option request should be a 200 returning an empty response. Then the browser will send the real POST request.
for that replace with the headers in your PHP File in the constructor. It will work.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}

Retrieving a parameter value from an httpClient response in angular6 with a php API?

I have a method in angular that posts values to a php api, when http post is successful, I get a json response, but when I try to access res.status or any parameter in the json object I get Property 'status' does not exist on type 'Object'. How can I get the value of a parameter in the response object?
Here is my angular class
export class QuizComponent implements OnInit {
constructor(private http: HttpClient) { }
myData = { param1: 'This is param 1', param2: 'this is param 2' }
sendmydata(){
const req = this.http.post('http://myhost.com/phpapi/api.php',this.myData)
.subscribe(
res => {
console.log(res);
// how can I access res.status here?
res.status;//this line says Property 'status' does not exist on type 'Object'
},
err => {
console.log("Error occured");
}
);
}
and here is my PHP :
(I know about prepared statements, just keeping it simple here):
<?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");
$db = "dbname";//Your database name
$dbu = "dbuser";//Your database username
$dbp = "dbpass";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$item1 = $request->param1;
$item2 = $request->param;
$sql = mysql_query("INSERT INTO `$db`.`table` (`id`,`item1`,`item2`)
VALUES ('','$item1','$item2');");
if($sql){
if (strcmp($item1, "") != 0) {
echo '{"status":"ok"}';
}
}else{
echo '{"status":"error"}';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
Assuming you have an interface defined for your response:
interface Response {
status: string;
}
Add the type information to your post call:
this.http.post<Response>('http://myhost.com/phpapi/api.php',this.myData)
or any, if no type definition available
this.http.post<any>('http://myhost.com/phpapi/api.php',this.myData)

.ajax post to external server php file causing 500 error

I have a php file on an second server that creates JWT Tokens using the Firebase Token Generator (https://github.com/firebase/php-jwt).
When I make a post using .ajax in my app, it keeps giving me a 500 error. I think that use \Firebase\JWT\JWT; in the php file may be causing this issue, but i am not sure why. Would appreciate any assistance with pointing me in the right direction.
Here is the PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?PHP
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);
}
// include('./config.php');
require_once '../vendor/firebase/php-jwt/src/BeforeValidException.php';
require_once '../vendor/firebase/php-jwt/src/ExpiredException.php';
require_once '../vendor/firebase/php-jwt/src/SignatureInvalidException.php';
require_once '../vendor/firebase/php-jwt/src/JWT.php';
$issuedAt = time();
$expire = $issuedAt + 86400; //add 24 hours
$personalID = $_POST['personalID'];
$email = $_POST['email'];
$key = "stringkeyexample";
$token = array(
"iss" => "example.com",
"aud" => "example.org",
"iat" => $issuedAt,
"nbf" => $issuedAt,
"exp" => $expire,
"pid" => $personalID
);
if ($puid){
use \Firebase\JWT\JWT;
$jwt = JWT::encode($token, $key);
print_r($jwt);
}
here is the .ajax:
$.ajax({
type: "POST"
, dataType: "html"
, url: "https://external-server.com/jwt.php"
, data: {personalID: personalID, email: email}
, beforeSend: function(){
console.log("before");
}
, complete: function(){
console.log("done");
}
, success: function(html){
console.log(html);
}
});

Categories