500 Internal Server Error From PHP - Insert Data Into VFP9 Database - javascript

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.

Related

Database not responding to form when input added

So my database does not add this data into the database when the button is pressed.
I have created a form, and all the id's are perfect and the email is a foreign key so it is taken from sessionStorage of the logged in user. I need help with why it is not working, I have no idea. The page alerts me "the order was successful" when I press submit but the data does not get stored in the database.
My SQL statement also works definitely, I tried it in my database.
Here are my php and js:
<?php
header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "leaf123";
$dbname = "laxmi";
// Create Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed:" . mysqli_connect_error());
}
else
{
// Obtain the contents
$request = file_get_contents('php://input');
// decode json so PHP can use it
$jsonRequest = json_decode($request);
// Query
$sql = "INSERT INTO checkout(email, ccName, ccNumber, month, year, cvc) VALUES ('$jsonRequest->email', '$jsonRequest->ccName', '$jsonRequest->ccNumber', '$jsonRequest->month', '$jsonRequest->year', '$jsonRequest->cvc')"
}
// Execute Query
$results = mysqli_query($conn, $sql);
echo json_encode("success");
mysqli_close($conn);
my javascript
$(document).ready(function () {
//When the submit button on the checkout form is pressed.
$("#SubmitOrder").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.getItem("loggedInUser");
var ccname = document.getElementById("ccName").value;
var ccnum = document.getElementById("ccNumber").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var cvc = document.getElementById("cvc").value;
//create an array with the details in.
var checkout = {
email: email,
ccname: ccname,
ccnum: ccnum,
month: month,
cvc: cvc,
}
//direct the user to the login page and alert them that their registration was successful.
alert("Your order was successful.")
window.location.href = "../index.html"
//posts the JSON object to the php file so it can fill the database, and converts the checkout array into JSON so it can be read.
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
})
})
First off, you're displaying the success message before even trying to send the post request to your PHP file. So your first job is to re-order things
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout));
alert("Your order was successful.");
window.location.href = "../index.html";
Secondly, you're currently not checking for a response from the server as to whether the request was successful or not. I've modified the example from the jQuery docs https://api.jquery.com/jquery.post/
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
.done(function() {
alert("Your order was successful.");
window.location.href = "../index.html";
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
Once you're done with that, you'll want to look into returning a response from PHP to say whether the query worked etc, but the above is at least enough to get you something that works for now :)

ajax-php connection error XML Parsing Error [duplicate]

So I'm making a simple login/registration web application but I keep getting the following error:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
and
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
here is my login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
I've done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox
AHA! Got this today for a reason which will make me look pretty silly but which might one day help someone.
Having set up an Apache server on my machine, with PHP and so on... I got this error... and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed "file:///D:/apps/Apache24/htdocs/experiments/forms/index.html".
What you have to do to actually use the Apache server (assuming it's running, etc.) is go "http://localhost/experiments/forms/index.html" in the browser's address bar.
In mitigation I have up to now been using an "index.php" file and just changed to an "index.html" file. Bit of a gotcha, since with the former you are obliged to access it "properly" using localhost.
I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue
#PostMapping()
public void aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
}
To
#PostMapping()
public String aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
return "justReturn something";
}
Assuming you are working with javascript, you need to put a header in front of echoing your data:
header('Content-Type: application/json');
echo json_encode($response);
Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.
If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.
Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form class="modal-content animate" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
<button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
<button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
</div>
</form>
JavaScript
function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
url: 'makeUserEntry.php',
type: 'POST',
data: datasend,
success: function(response, status) {
if(response=="Username or Password did not match"){
alert("Username or Password did not match");
}
if(response=="Connection Failure"){
alert("Connection Failure");
}
else{
localStorage.userid = response;
window.location.href = "./maze.html"
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, php script returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
}); // end ajax call
}
PHP
<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];
//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
$userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$userID = $conn->query($userIDSQL);
echo json_encode($userID);
}
else{
echo json_encode("Username or Password did not match");
}
$conn->close();
?>
It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!

AJAX function for retrieving postgres data not working

I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}

XML Parsing Error: no root element found

I am trying to search for all properties in a database that are in one suburb. I have read that it has something to do with the HTML code 204 but I still do not undertand what to do or what it really means. I have not done any JS or PHP in a while so this may be a really silly error but I cannot for the life of me figure it out. Please Help!
Here is my JS code:
function basicSearch(){
//Connect Script to the PHP
var urlLink = "basicSearch.php";
//Get search parameters:
var searchAreaBar = document.getElementById("searchAreaBar").value;
//define the parameters to send to php
var strParameters = "searchAreaBar="+searchAreaBar + "&sid=" + Math.random();
// define the options for the AJAX request
var objOptions = {
// use method post
method: "post",
// use strParameters as the parameters
parameters: strParameters,
// if successfil call fuction(objXHR)
onSuccess: function(objXHR) {
// if objXHR. responseText = yes
if(objXHR.responseText=='Yes'){
alert("Success!");
}
else{
alert("Error! No Properties Found!");
}
}
}
// define the AJAX request object
var objRequest = new Ajax.Request(urlLink,objOptions);
}
Here is my PHP code:
<?php
//Link the username and password:
$connect = mysqli_connect("localhost", "admin", "12345", "realestate") or die ('Connection to database failed: ' . mysql_error());
//Extract variables for request parameters:
extract($_REQUEST);
//Define the query:
$BasicSearch = "SELECT * FROM properties WHERE Suberb='$searchAreaBar'";
//Run the query:
$resDasicSearch = mysqli_query($BasicSearch) or die(mysql_error());
//SET intCount to number of rows in result:
$intCount = mysqli_num_rows($resDasicSearch);
//If intCount is greater than 0:
if($intCount > 0){
//Echo Yes:
echo "Yes";
}
else{
//Echo no:
echo "No";
}
?>
Thanks in advance.
The error was that the browser's compiler was "commenting out" all the php and adding empty HTML tags. It was then getting confused as there was an "empty" document.
This was because the website (including JS, PHP and HTML files) were being stored and run from a local directory. For example:
the URL read:
file:///C:/xampp/htdocs/"Project Name"/Index.html
the correct URL is:
localhost/"Project Name"
IF you are using XAMPP, the folder containing all your project files need to be placed in the htdocs folder in the xampp directory.
As you seem to be using an Ajax function that is not shown it is hard to determine the root cause of the problem because nothing above, as far as I can tell, would yield the error you allude to in the title of the posting - namely "XML Parsing Error: no root element found" - I wonder therefore if there should be a configuration option in Ajax.Request that needs to be set to deal with a basic string response?
That aside you might be able to make use of the following - perhaps even for diagnosis purposes.
<?php
/*
---------------
basicSearch.php
---------------
*/
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpwd = '12345';
$dbname = 'realestate';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql='select * from `properties` where `suberb`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$searcharea = $_POST['searchAreaBar'];
$stmt->bind_param( 's', $searcharea );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $suberbs );
$stmt->fetch();
echo $stmt->num_rows()==0 ? "No" : "Yes";
}
$stmt->close();
$db->close();
?>
<script>
/* reuseable utility ajax function */
function ajax( method, url, params, callback, options ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response, options, xhr.getAllResponseHeaders() );
};
var async=params.hasOwnProperty('async') ? params.async : true;
var query=[];
for( var n in params )query.push(n+'='+params[n]);
switch( method.toLowerCase() ){
case 'post': query=query.join('&'); break;
case 'get': url+='?'+query.join('&'); params=null; break;
}
xhr.open( method.toUpperCase(), url, async );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
}
/* function that does the search */
function function basicSearch(){
/* configure the parameters to be used in the ajax request */
var method='post';
var url='basicSearch.php';
var params={
searchAreaBar:document.getElementById('searchAreaBar').value,
sid:Math.random()
};
var callback=function(r,o,h){
alert( r ? 'Success' : 'Error! No Properties Found!' )
}
var options={};
/* call the ajax function */
ajax.call(this,method, url, params, callback, options);
}
</script>
Today I meet this error in Firefox's console, that is so simple, while all my API return JSON, one of my API return text/html and it causes Firefox show up that error!
I have changed my NodeJS Express code:
res.end('');
To
res.json({});
ANd it is okay now! Hope it can help someone!

AngularJS SlimPHP CRUD - $http.delete doesn't work - XMLHttpRequest cannot load

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}.

Categories

Resources