Why does my website think the $http request is cross domain? - javascript

In my website I'm calling to a php page at http://domain.com/angulartest/js/services/index.php
from a service in the same folder.
app.factory('vakmannen', ['$http', function($http) {
return $http.get('http://www.domain.com/angulartest/js/services/index.php')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and this is my php
<?php
header("Access-Control-Allow-Origin: http://www.domain.com/angulartest/");
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM XXXX";
$result = $conn->query($sql);
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
?>
But every time the $http.get runs Firefox tells me the CORS header isn't right, I've tried it on Chrome too but to no avail.
Any help will be greatly appreciated!

If the angular app is in the same folder, you can use relative URLs. You can even remove the Access-Control-Allow-Origin header.
app.factory('vakmannen', ['$http', function($http) {
return $http.get('/angulartest/js/services/index.php')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);

Related

Post method return Json data keeps on looping

So, I am building a website that tries to first post an id from the front end then on the php file. The post method return a questions that is base on the id that is send to the backend and query through the database. This is my code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET,POST");
header("Content-Type: application/json; charset=UT-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$servername = "localhost";
$username = "root";
$password = "";
$database= "credentials";
// Create connection
$db = mysqli_connect($servername, $username, $password, $database);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)){
$request = json_decode($postdata);
$quizID = $request->QuizID;
$sql = "SELECT * FROM question WHERE QuizID='$quizID'";
$result = mysqli_query($db,$sql);
if(mysqli_num_rows($result)>0){
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
$response = ["data"=>"valid","quiz"=>$json_array];
echo json_encode($response);
}else{
$response = ["data"=>"invalid"];
echo json_encode($response);
}
}
?>
The front end was successfully return the JSON data but it keeps looping non stop. Why is that happening, I tried running the query first then I store in variable but still it keeps looping.
This is my front end code
useEffect(()=>{
console.log("use effect");
const sendData = {
QuizID: localStorage.getItem("quizID")
}
console.log("adad")
axios.post("http://localhost/pepep/fetchLesson.php", sendData).then(res=>{
console.log("post success");
console.log(res.data.quiz[0]);
setQuestion([res])
})
})
Can anyone help me with this ?
You have setQuestion([res]) which will set the state to a new value.
Setting the state will trigger a re-render.
Your useEffect call doesn't have a dependency array, so it will run on every render.
Add a dependency array with a list of variables that should trigger the function when they change.
Since you don't appear to be using any external variables, it looks like that should be none.
useEffect( () => { /* ... */ }, [] );

what can i do to access only a specific table

I 'm working at with XAMPP server at my home pc.My files are in xampp/htdocs/marfo I am trying to fetch some records in a booking database lying on xampp\mysql\data\marfo. Althought i can read all others tables of the same database (using different files at the same directory) this specific table gives me this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/xampp/htdocs/marfo/booking.php. (Reason: CORS request not http)."
the code in js is:
function readres() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responceText != "NoResults") {
reservarray = JSON.parse(this.responseText);
// function to set whole site for this language
} else { return "Bad thing !!! Something went wrong .........." }
} else { return "Didn't found anything malaka.........." }
}
xmlhttp.open("GET", "booking.php", true);
xmlhttp.send();
}
and the code at PHP file:
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'marfo';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed:" . $conn->connect_error);
}
$sql = "SELECT * FROM bookings";
$result = $conn->query($sql);
$counter = 0;
if ($result->num_rows > 0) {
// output reservations
while ($row = $result->fetch_assoc()) {
$reservarray = array(
"datefrom" . $counter => $row["datefrom"], "dateto" . $counter => $row["dateto"], "name" . $counter => $row["name"]
);
$counter = $counter + 1;
}
echo json_encode($reservarray);
} else {
echo 'No results';
}
$conn->close();```
any help appreciated....

cannot get data to javascript from php DB

I am quite new to JavaScript and PHP.
I have started lately on my free time to develop a chrme extension to grab some data from db on a hosting server.
I have created a php file and upload it to the server, this file will be called from my extension js file and will connect to the DB to execute a query and return the result back.
everything goes fine except I dnt see the data, it keeps sending me null info.
Connection is ok, credentials are good but somiething is missing.
PHP code:
<?php
header("Access-Control-Allow-Origin: *");
$name = $_POST['name'];
$servername = "139.162.132.71";
$username = "evhoodco_EVhdAdm";
$password = "******";
$dbname = "evhoodco_EVhd623Vehicles";
// Create connection
$dbhandle = new mysqli($servername, $username, $password, $dbname);
if (!$dbhandle)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
echo "Success to connect to MySQL";
}
$result = $dbhandle->query("SELECT 1");
if ( false===$result ) {
printf("error: %s\n", mysqli_error($con));
}
else {
echo ' ... done...';
}
echo json_encode($result);
mysqli_close($dbhandle);
?>
JavaScript code:
$(document).ready(function(){
$.post('http://evhood.com/connDB.php','name=bob').done(function(data){
chrome.bookmarks.create({'parentId': "1",'title': '','url': "http://www.sapo.pt"});
console.log(data);
});
});
And this is the debug window result:

Vue.js 2 + API created with PHP microframework Slim

I'm learning how to create an API and connect it with Vue.js application.
I need to create a users' registration form.
Is it correct if I create an API with PHP and then connect it to my Vue.js in order to register users. An API will be connected to MySQL db.
Here's my db.php class:
class DB {
private $dbhost = 'localhost';
private $dbuser = 'root';
private $dbpass = '';
private $dbname = 'organization';
public function Connect() {
$mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if ($mysqli->connect_errno) {
echo "Не удалось подключиться к MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
return $mysqli;
}
}
And this is one of routes:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$app->get('/api/customers', function(Request $request, Response $response) {
$db = new DB();
$db = $db->Connect();
$sql = "SELECT * FROM workers";
$result = $db->query($sql);
echo json_encode($result->fetch_assoc());
$db->close();
});

Ionic Angular pass data to PHPfile and insert into MySQL database

Something strange happen, I pass insert data from angular controller to php file. Next, php file is inserting data into MySQL database. All the data is successfully inserted. However once I click on button two record is inserted into MySQL database. One will the empty data is inserted and second is the data I entered from UI. The following is my code:
Javascript controller Code:
.controller('registerController',['$scope', '$stateParams', '$state', '$http', function($scope, $stateParams, $state, $http){
var userInformation = [];
$scope.registration = {};
console.log($stateParams.all);
$scope.doRegister = function () {
if( $scope.registration.pasword !== $scope.registration.confirmpassword){
alert("Password not match");
}
$http({
url: "http://localhost/php/chat.php",
method: "POST",
data: {
'username': $scope.registration.username,
'email': $scope.registration.emailaddress,
'password': $scope.registration.pasword
}
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
});
$state.go('login', {userInformation : userInformation});
};
$scope.goBack = function() {
$state.go('login');
}
}])
PHP Code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user = $request->username;
$email = $request->email;
$pass = $request->password;
$servername = "localhost";
$username = "jack";
$password = "1234";
$dbname = "chat";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO use_directory VALUES ('', '$user', '$email', '$pass');" ;
$retval = $conn->multi_query($sql);
if( $retval === TRUE) {
echo "Add successfully\n";
}else {
die('Could not edit data');
}
?>
Here is my database outcome
$sql = "INSERT INTO use_directory (user,email,pass) VALUES ( '$user','$email', '$pass')" ;
if(mysqli_query($conn, $sql)){
echo "Add successfully\n";
}else{
die('Could not edit data');
}
Have you tried like this? Hope it helps :)

Categories