Have an issue making a CRUD using AngularJS and SlimPHP v3. Everything works for $app->get and $app->post but got an error for an $app->delete.
I have frontend and backend on different domain names, because I had to set htaccess to redirect everything to index.php for Slim to work, so didn't succeed on putting front and back on same domain.
This is my index.php
<?php
require __DIR__ . '/vendor/autoload.php';
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
$app = new \Slim\App();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$app->options('/test', function() use($app) {
$response = $app->response();
$app->response()->status(200);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
$app->get('/test/', function(Slim\Http\Request $request, Slim\Http\Response $response, array $args) {
$id = $args['id'];
$sql = "SELECT * FROM wp_osoft_orders";
$dbhost = "host";
$dbuser = "user";
$dbpass = "pass";
$dbname = "db";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$headers = $response->getHeaders();
$response = $response->withHeader('Content-type', 'application/json');
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$headers = $response->getHeaders();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultsArray = array();
while($row = $result->fetch_assoc()) {
array_push($resultsArray, $row);
}
$response->write(json_encode($resultsArray));
}
else {
$response->write("0 results");
}
$conn->close();
});
$app->delete('/test/{id}', function(Slim\Http\Request $request, Slim\Http\Response $response, array $args) {
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response->write("delete is OK");
});
$app->run();
?>
And this is my Angular code:
function getOrders(){
$http.get("url/test/").success(function(data){
$scope.orders = data;
});
};
getOrders();
$scope.deleteOrder = function (orderId) {
console.log("order to delete id: " + orderId);
$http.delete("url/test/"+orderId).success(function(response){
console.log('delete response: ' + response);
});
getOrders();
};
Order Id I got correctly to the console.log in Angular, but then I get:
DELETE url/test/22
XMLHttpRequest cannot load url/test/22. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'url' is therefore not allowed access. The response had HTTP status code 400.
Every time i wrote url/ i mean http://mywebsite.com, but was unable to posta question with 2+ links.
Thanks for your help.
CorsSlim is your friend and it's the simpler way to enable CORS in the Slim Framework world. Install it using composer and use it:
$app->delete('/test/{id}', function(Slim\Http\Request $request, Slim\Http\Response $response, array $args) {
$response->write("delete is OK");
})->add(\CorsSlim\CorsSlim::routeMiddleware());
In this way you'll be sure that the request will contain the necessary headers.
Side note
In your example you're using $app->options only on /test and not on /test/{id}.
Related
full erorr
Access to XMLHttpRequest at 'https:/domain/errors/403/' (redirected from 'http://domain/includes/action.php') from origin 'domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://domain' that is not equal to the supplied origin.
the code should to search without refresh so in localhost all work right but when i go to server i got this erorr in console
here is my php where i got a response to my main page
<?php
include 'db.php';
if (isset($_POST['search'])) {
$Name = $_POST['search'];
$Query = "SELECT * FROM items WHERE name LIKE '%$Name%' OR namea LIKE '%$Name%' LIMIT 6";
$q2 = "SELECT * FROM items WHERE namea LIKE '%$Name%' LIMIT 6";
$ExecQuery = mysqli_query($con, $Query);
$ExecQuery2 = mysqli_query($con, $q2);
if ($ExecQuery) {
$go = $ExecQuery;
} else {
$go = $ExecQuery2;
}
echo '<ul class="cards">';
while ($row = mysqli_fetch_array($go)) {
$name = $row['name'];
$p = $row['price'];
$d = $row['descrip'];
$m = $row['img'];
echo '
<li class="cards__item">
<div class="card">
<img src="pimg/' . $m . '" class="card__image">
<div class="card__content">
<div class="card__title">name: ' . $name . '</div>
<div class="card__title">price: ' . $p . ' $</div>
<p class="card__text">' . $d . '</p>
</div>
</div>
</li>';
}
}
here is my js code to send the data to search.php and got the response
function fill(Value) {
$('#search').val(Value);
$('#display').hide();
}
$(document).ready(function () {
$("#search").keyup(function () {
var name = $('#search').val();
if (name != "") {
$.ajax({
type: "POST",
url: "includes/search.php",
data: {
search: name
},
success: function (html) {
$("#display").html(html).show();
}
});
}
});
});
First make sure that the code is fully error free, then please try something like following. I don't know exactly it solve your issue. Just try.
<?php
ob_start();
include 'db.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS');
header("Access-Control-Allow-Headers: X-Requested-With");
if (isset($_POST['search'])) {
// do the things you needfull
}
ob_end_flush();
You will get more information about Cross-Origin Request Headers(CORS) with PHP headers from here. Please check the answers in the link above mentioned.
I'm trying to write an API script in PHP to insert records into a Foxpro 9 database but i'm getting the "500 Internal Server Error" message when the API is called. I'm a Foxpro developer but pretty new to PHP.
I've gone through several questions & comments on the topic on this site and other sites and have implemented almost all of the suggested solutions to no avail. Below are the steps i've taken so far:
IIS & PHP are installed and configured. (phpinfo() is displaying correctly)
VFP 9 is fully installed. (with VFPOLEDB driver)
I've fully cleared browsing data severally.
I'm not sure where the problem is (as the "500 internal server error" message could be a problem with the PHP script or PHP configuration. Could somebody please take a look at the PHP script below to help figure out the problem?
TIA.
<?php
// required headers
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");
// database connection
$conn = new COM("ADODB.Connection");
$conn->Open("Provider=VFPOLEDB.1;Data Source=C:\inetpub\wwwroot\sonreceipt\RECEIPT.DBC;Collating Sequence=Machine");
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set payment values received
$jrefnum = $data->refnum;
$jpaydate = $data->paydate;
$jcustname = $data->custname;
$jcustemail = $data->custemail;
$jdemandno = $data->demandno;
$jdemanddate = $data->demanddate;
$jamount = $data->amount;
$jrecpdesc = $data->recpdesc;
$jpaybank = $data->paybank;
$jpayref = $data->payref;
// create the payment
if(create()){
echo "Payment was created.";
}
// if unable to create the payment, tell the user
else {
echo "Unable to create payment.";
}
// create payment
function create(){
// query to insert record
$query = "INSERT INTO SON2100 (refnum, paydate, custname, custemail, demandno, demanddate, amount, recpdesc, paybank, payref)
VALUES ($srefnum, $spaydate, $scustname, $scustemail, $sdemandno, $sdemanddate, $smount, $srecpdesc, $spaybank, $spayref)";
// prepare query
global $conn
$stmt = $conn->prepare($query);
// sanitize
global $jrefnum, $jpaydate, $jcustname, $jcustemail, $jdemandno, $jdemanddate, $jamount, $jrecpdesc, $jpaybank, $jpayref;
$srefnum=htmlspecialchars(strip_tags($jrefnum));
$spaydate=htmlspecialchars(strip_tags($jpaydate));
$scustname=htmlspecialchars(strip_tags($jcustname));
$scustemail=htmlspecialchars(strip_tags($jcustemail));
$sdemandno=htmlspecialchars(strip_tags($jdemandno));
$sdemanddate=htmlspecialchars(strip_tags($jdemanddate));
$samount=htmlspecialchars(strip_tags($jamount));
$srecpdesc=htmlspecialchars(strip_tags($jrecpdesc));
$spaybank=htmlspecialchars(strip_tags($jpaybank));
$spayref=htmlspecialchars(strip_tags($jpayref));
// execute query
if($stmt->execute()){
return true;
}
return false;
}
?>
Below is the javascript that calls the API.
<script>
function sendData(data) {
var XHR = new XMLHttpRequest();
var jsonData = {"refnum":"1111-2222-3333", "paydate":"01-06-2018", "custname":"O. A. BECKLEY VENTURES", "custemail":"beckleyventures#gmail.com", "demandno":"DEMAND NOTE 001", "demanddate":"01-06-2018", "amount":"15550.00", "recpdesc":"SONCAP", "paybank":"ZENITH BANK PLC", "payref":"0123456789"};
// Define what happens on successful data submission
XHR.addEventListener('load', function(event) {
window.alert('Yeah! Data sent and response loaded.');
});
// Define what happens in case of error
XHR.addEventListener('error', function(event) {
window.alert('Oops! Something goes wrong.');
});
// Set up our request
XHR.open('POST', 'http://localhost/sonreceipt/api/create_payment.php', true);
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Finally, send our data.
XHR.send(jsonData);
}
</script>
Here is the edited script but still not working. As indicated earlier, i'm still new to PHP.
<?php
// required headers
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");
// database connection
$conn = new COM("ADODB.Connection");
try {
$conn->Open('Provider=VFPOLEDB.1;DSN=RECEIPT;Mode=ReadWrite;Password="";Collating Sequence=MACHINE;');
if (! $conn) {
throw new Exception("Could not connect!");
}
}
catch (Exception $e) {
echo "Error (File:): ".$e->getMessage()."<br>";
}
if (!$conn)
{exit("Connection Failed: " . $conn);}
echo "Connection Sucessfull";
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set payment values received
$jrefnum = $data->refnum;
$jpaydate = $data->paydate;
$jcustname = $data->custname;
$jcustemail = $data->custemail;
$jdemandno = $data->demandno;
$jdemanddate = $data->demanddate;
$jamount = $data->amount;
$jrecpdesc = $data->recpdesc;
$jpaybank = $data->paybank;
$jpayref = $data->payref;
// create the payment
if(create()){
echo "Payment was created.";
}
// if unable to create the payment, tell the user
else {
echo "Unable to create payment.";
}
// create payment
function create(){
global $conn;
global $jrefnum, $jpaydate, $jcustname, $jcustemail, $jdemandno, $jdemanddate, $jamount, $jrecpdesc, $jpaybank, $jpayref;
// sanitize
$srefnum=htmlspecialchars(strip_tags($jrefnum));
$spaydate=htmlspecialchars(strip_tags($jpaydate));
$scustname=htmlspecialchars(strip_tags($jcustname));
$scustemail=htmlspecialchars(strip_tags($jcustemail));
$sdemandno=htmlspecialchars(strip_tags($jdemandno));
$sdemanddate=htmlspecialchars(strip_tags($jdemanddate));
$samount=htmlspecialchars(strip_tags($jamount));
$srecpdesc=htmlspecialchars(strip_tags($jrecpdesc));
$spaybank=htmlspecialchars(strip_tags($jpaybank));
$spayref=htmlspecialchars(strip_tags($jpayref));
// query to insert record
$query = "INSERT INTO SON2100 (refnum, paydate, custname, custemail, demandno, demanddate, amount, recpdesc, paybank, payref)
VALUES ($srefnum, $spaydate, $scustname, $scustemail, $sdemandno, $sdemanddate, $smount, $srecpdesc, $spaybank, $spayref)";
// prepare query
$stmt = $conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
?>
You haven't declared the variables used in the value portion of the SQL in your create() function and you're missing a semicolon
// you have
global $conn
// should be
global $conn ;
Use
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
to find your error.
I'm trying to get my app run into my if statement but it went down to else statement which is not what I want. callback data is "Pass" which is correct for my if condition but it still ran down to else. Please take a look at my code.
js file
$http.post(path, postdata
).success(function (data, status, headers, config) {
//if (data) {
// $scope.PostDataResponse = data;
if (data === "Pass"){
setCookie("Username", $scope.formdata.Username);
setCookie("cafe_id", $scope.formdata.cafe_id);
console.log(getCookie("Username"));
alert("ลงทำเบียนสำเร็จ !");
$location.url('/viewSaveCafeDetail');
//console.log(data);
//alert("สมัครสมาชิกสำเร็จ");
//$scope.insertcafe();
//$scope.sendEmail();
// $scope.reset();
// $scope.getData();
}else{ <--- ran down to else statement
alert(data); <--- callback value is "Pass" which is match with my if condition.
}
PHP file
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods : GET,POST,PUT,DELETE,OPTIONS");
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Requested-With, X-YOUR-CUSTOM-HEADER');
header("Content-Type : application/json");
header("Accept : application/json");
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "middlework";
$conn = new mysqli($serverName,$userName,$userPassword,$dbName);
mysqli_set_charset($conn,"utf8");
session_unset();
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$strSQL = "INSERT INTO users ";
$strSQL .="(Username,Password,Firstname,Lastname,Email,Tel,AccountStat,VerifyCode,Verifystat) ";
$strSQL .="VALUES ";
$strSQL .="('".$request->Username."','".$request->Password."','".$request->Firstname."' ";
$strSQL .=",'".$request->Lastname."','".$request->Email."','".$request->Tel."','User','".session_id()."','None' ) ";
mysqli_query($conn,$strSQL) or die(mysqli_error($conn));
$insertcafe = "INSERT INTO cafe (cafe_id,Username,CafeName) VALUES ('1' , '".$request->Username."', '".$request->CafeName."')";
require_once('PHPMailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->CharSet = "utf-8";
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "kitsakorn.p55#rsu.ac.th"; // GMAIL username
$mail->Password = "1100501068349"; // GMAIL password
$mail->From = "kitsakorn.p55#rsu.ac.th"; // "name#yourdomain.com";
$mail->FromName = "ThaiCoffeeShopOnline"; // set from Name
$mail->Subject = "ยืนยันการสมัครสมาชิก ThaiCoffeeShopOnline";
$mail->Body = "ขอขอบคุณที่สมัครเป็นสมาชิกกับเรา กรุณาคลิก Url ด้านล่างเพื่อทำการ Activate บัญชีของคุณ</br>
http://localhost/activate.php?sid=".session_id()."&uid=".$request->Username."</br></br> ThaiCoffeeShop.com";
$mail->AddAddress($request->Email); // to Address
if($conn->query($insertcafe))
{
if (!$mail->send()) {
//echo "ไม่สามารถส่ง email: " . $mail->ErrorInfo;
echo "EmailFail";
} else {
echo "Pass ";
//json_decode();
}
//echo "Save Cafe Done.[".$insertcafe."]";
}
else
{
echo "";
//echo mysqli_error($conn);
//echo "ไม่สามาถบันทึกข้อมูล[".$insertcafe."]";
}
$conn->close();
?>
Your PHP file has echo "Pass "; which writes "Pass" followed by a space which you are comparing against the string "Pass" without a space.
In addition, you might also have a blank line at the end of your PHP file which will also be included in the output. This can be worked around by removing the ?> tag from the end.
I have an API based on Php Slim Framework and want to generate JSONP for my website. When I call the website on: 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK'. It returns a blank page with JSON CALLBACK() write on it. When logged to the console it is undefined.
API's index.php:
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/users', 'getUsers');
$app->run();
function getConnection() {
$dbhost="localhost";
$dbuser="";
$dbpass="";
$dbname="";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;mysql:charset=utf8mb4", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getUsers() {
$sql = "select * FROM manga";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo $_GET['callback'] . '('.json_encode($users).')';
}
catch(PDOException $e) {
echo $_GET['callback'] . '('.json_encode($e->getMessage()).')';
}
}
Javascript:
.factory('MY', function($http){
var fax= {};
var url = 'http://api.mangayurdu.com/users?callback=JSON_CALLBACK';
fax.isimler = $http.jsonp(url);
return fax;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen){
$scope.mangas = alHemen;
});
})
Don't serve it as application/json. Serve it as application/javascript. JSONP needs to be executed.
Also it appears with Slim you shouldn't use echo. Try calling $app->response->setBody.
I know this question has been asked before but none of the solutions I have tried work, I wrote a php rest service which I'm hosting on a server, I used advanced rest client data on chrome to test my rest service and it works, it posts data to the database, but when I wrote my own client in an ajax post below the browser complains of
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8383' is therefore not allowed
access.
I have tried adding a header to my php code still doesn't work i get another error..., I'm just wondering what I'm doing wrong?
>// MY PHP REST SERVICE
<?php
$servername = "localhost";
$username = "root";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
// Get data
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Insert data into data base
$sql = "INSERT INTO UserData.register (name, surname, email, password)
VALUES ('$name', '$surname', '$email','$password')";
if ($conn->query($sql) === TRUE) {
$json = array("status" => 1000, "msg" => "Done User added!");
} else {
$json = array("status" => 0, "msg" => "Error adding user!");
}
header('Content-type: application/json');
echo json_encode($json);
$conn->close();
}
> //MY java script ajax client doing the posting.
<script type="text/javascript">
function RegisterUser() {
var name = $("#name").val();
var surname = $("#surname").val();
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "http://xxx.xxx.xxx.xxx/signup.php",
data: '{"name":"' + name + '","surname":"' + surname + '","email":"' + email + '","password":"' + password + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d)
}
});
}
</script>
Try Using .htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
CORS guide is here which lists all the possible ways to solve the problem regarding CORS.