AngularJS: cannot POST to server PHP file (getting 404) - php

Hi All and thanks for your time!
I am new to AngularJS and currently working on my first form with server side part.
I am running on VirtualBox, used Yeoman to set up.
my HTML has 2 fields: username and password, that are in turn passed to the js file:
function authUsers($scope, $http) {
$scope.url = '../api/authUsersService.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.loginAttempt = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
alert($scope.session.username);alert($scope.session.password);
$http.post($scope.url, { "username" : $scope.session.username, "password" : $scope.session.password}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
alert(data);
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert(data);
alert(status);
});
};
}
I am getting the 2 alerts (username, password).
This file and the HTML itself is under Angular's APP folder. outside the folder, in the same containing folder: I created 'API' folder. this is the file api/authUsersService.php:
<?php
$data = file_get_contents("php://input");
$objData = json_decode($data);
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "select userID from authUsers where username = " . $objData->username . " and password = " . $objData->password);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row["userID"];
} else {
echo "";
}
?>
when the HTML form is submitted, i am getting all the alerts from the controller (js file), including the ".error" ones. the data i am getting inside the error: "cannot post to /api/authUsersService.php" and the status is "404".
i couldn't find any solution. tried an .htaccess in the var\www\http folder, didnt help.
please help me successfully get to the PHP server code!
thanks!

Using "../" in a URL is a good indicator you're doing something wrong.
You can't go "outside" the root directory of your webserver, so you need to put it inside the "app" directory, so that it's web accessible.

Related

Ajax POST call to PHP

I'm trying to send a string from my JS file to my PHP file with an AJAX POST call and then insert that string into my Wordpress database.
I am able to send the string however I get this error message:
Notice: Undefined index: data in C:\Bitnami\wordpress-5.0.3-2\apps\wordpress\htdocs\wp-content\plugins\Kalkylator\templates\create.php on line 81
line 81 is: $data = $_POST['data'];
JS FILE
$(document).ready(function() {
var testingString = "hello people";
$.ajax({
url: "admin.php?page=jvformbuilder_create",
method: "POST",
data: { 'data': testingString },
success: function(result) {
console.log("result: " + result);
},
error: function(error) {
console.log("error: " + error);
}
});
});
PHP FILE
$data = $_POST['data'];
echo $data;
insertToDB($data);
function insertToDB($data)
{
$db = new mysqli('localhost', 'root', 'password', 'bitnami_wordpress');
if ($db->connect_errno > 0)
{
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Attempt insert query to database.
$testing = "INSERT INTO wp_test (value) VALUES ('$data')";
mysqli_close($db);
}
Here is the file structure
I am currently working on my happypath hence why I don't validate the input to the database.
All help and tips are welcome, thanks in advance :D
Edit: I managed to solve the problem, it was like alot of people suggested that the data was being redirected in admin.php. so I just moved my php function there and now it works (atleast for my happypath). Thanks alot to all who took their time to help :D
You need to pass $data to the insertToDB() function. You currently reference it like this:
$data = $_POST['data'];
echo $data;
insertToDB ();
You need to do this:
$data = $_POST['data'];
echo $data;
insertToDB ($data);

AngularJS form data not stored in MySQL db

In my AngularJS app, the data entered into the form are not stored in the MySQL database after hitting the submit button. An alert after successful form data submit however indicates that it is working.
Also, after hitting the submit button, I want the app to proceed to the next view (#/setup-step2) - however it remains at step1.
html partial (#/setup-step1):
<form ng-submit="submitForm1()">
Job title: <input type="text" name="jobtitle" ng-model="formData1.jobtitle">
Vacancy ID: <input type="text" name="vacancyid" ng-model="formData1.vacancyid">
<button type="submit" class="animatedbutton"> Proceed </button>
</form>
controller.js:
var ctr = angular.module('myApp.controller', []);
ctr.controller
('Step1Controller', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.formData1 = {};
$scope.submitForm1 = function() {
$http({
method: 'POST',
url: 'php/setup-step1.php',
data: $.param($scope.formData1),
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log(data);
alert("It worked");
})
.error(function(data) {
console.log(data);
alert("It didn't work");
})
}
}]);
setup-step1.php in folder /php:
<?php
include_once('db.php');
// Check connection
if(mysqli_connect_errno())
{echo '<p>Connection to MySQL server failed: '.mysqli_connect_error().'</p>';}
else
{echo '<p>Connection to MySQL server successful.</p>';}
$_POST = json_decode(file_get_contents("php://input"), true);
if (empty($_POST['jobtitle']))
{$errors['jobtitle'] = 'Job title is required.';}
else {
// Escape user inputs for security
$jobtitle = $_POST['jobtitle'];
$vacancyid = $_POST['vacancyid'];
$data = "INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle','$vacancyid')";mysql_query("INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle', '$vacancyid')");}
if ($connect->query($data) === TRUE)
{$conn->close();}
else
{echo "Error: " . $sql . "<br>" . $conn->error;}
exit();
?>
First,
Be sure that you enable the cors before performing any request to the server.When you are working with angularjs this usually means that you are making cors requests to the server.If you didn't enable cors option you cannot call any method from the server since it is not allowed.
Second,
just keep php code inside your setup-step1.php.You don't need any html code there since it will return result of your requet only.
Third,
As I know you cannot change location of the webpage from erver because server domin and website domains are different.You need to redirect the user to another page in angularjs. You can find the ways of redirecting in angularjs by using $location or $state.
I found the answer myself. The problem was incorrect php and mysql syntax. Updated the code the way it works now.

File Upload Using AngularJS with php server script

I have reviewed the questions and answers on this topic and I dont think they fully answer my issues which are:
the upload using the angular frontend (whichever way this is handled) sends the file data to a script on the server such as a php script (which is my preferred method). Once the php script has run I want to return to the page from which the upload was made and give a message there..I dont want the php page to display. Will appreciate some guidance on how to achieve this. Ideally what code to add to the php script.
I want to capture and save to a database info relating to the file such as its name and data entered/selected by the user such as a document category. Is there a way to achieve this as part of the file upload? ie ideally the user will complete entries in a form which includes a file upload button so that the user selects the file to upload but only on the form submit being clicked is the file upload actioned along with the other form data being returned for processing.
I have spent 3 days on this.. so any help will be great.
You can use FormData objects to send form data to your server.It will allow you to send both files and text data at the same time. You can find more information about it here.
index.html
<body ng-controller="myCtrl">
<div class="file-upload">
<input type="text" ng-model="name">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</body>
In app.js, we create a custom directive fileModel, in which we listen for changes to the content of the input element and change the value of the variable in the scope accordingly. This is achieved using the $parse service to set the value in our scope.
app.js
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
// We can write our own fileUpload service to reuse it in the controller
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl, name){
var fd = new FormData();
fd.append('file', file);
fd.append('name', name);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined,'Process-Data': false}
})
.success(function(){
console.log("Success");
})
.error(function(){
console.log("Success");
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "save_form.php";
var text = $scope.name;
fileUpload.uploadFileToUrl(file, uploadUrl, text);
};
}]);
save_form.php
<?php
$target_dir = "./upload/";
$name = $_POST['name'];
print_r($_FILES);
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
//write code for saving to database
include_once "config.php";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyData (name,filename) VALUES ('".$name."','".basename($_FILES["file"]["name"])."')";
if ($conn->query($sql) === TRUE) {
echo json_encode($_FILES["file"]); // new file uploaded
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Passing an array from PhP to jQuery using JSON and $.ajax

First off, I apologise since this is my first time working with JSON.
My website has a client script that requests person data from the server. The server first queries the database (using mysql and mysqli) and then returns the data (names, ages, etc.) to the client side.
Specifically, I want to pass an associative array from the PhP side to the client side.
After doing some research, I decided to do this with AJAX JSON calls.
The client side call is done like this:
var person_id = $('#my_text_box').val();
$.ajax({
url: 'php/upload/my_server_script.php',
method: 'POST',
data: {id: person_id},
dataType: 'json',
cache: false,
success: function(response_data)
{
alert(response_data['name']); //The server should return an associative array
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log(jqXHR.responseText);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
The server side calls a method that will query the database and give the details of the person with the requested ID.
$id = $_POST['id'];
function getPersonData($id)
{
$personData = array();
(1 - Connect and SELECT name FROM Persons WHERE id = {$id}
2 - Fill the $personData array with result row
3 - Name will be saved in $personData['name'])
return json_encode($personData);
The AJAX call fails with the error 500 - Internal Server Error. When I check the contents of the server response on the browser (On Chrome, Network tab), it says there is no response (This request has no response data available).
The thing is, this code works perfect locally. But when I upload it to my cloud web server, the only AJAX calls in my website that fail are the ones that use JSON as the format for the data being transferred. The other ones work fine.
A couple of things I've tried:
First, checking if the array on the PhP side is empty or built with errors. It's not, all the correct values are there;
Second, including application/json to the cloud web server mime.type file (It's Apache);
Then, including a header('Content-Type: application/json'); in my server-side script.
Also, adding "contentType: 'application/json' " to the client-side $.ajax.
None of these four worked. What could I be forgetting?
Note: The browser's log reads as follows:
Arguments[3]
0: Object
1: "error"
2: "Internal Server Error"
callee: function (jqXHR, textStatus, errorThrown)
length: 3
__proto__: Object
*(url of my script file)*
Error: Internal Server Error error [object Object] ^
Note #2: Full PhP code:
//Fetch persondata for a specific ID, and encode the data in an array in JSON format
function JSONSelectPersonDataFromID($ID)
{
$personData = array(); //Array or array with results
//If querysuccess, commit. Else, rollback
$querySuccess = True;
//This method opens connection with root user
$conn = OpenDBConn();
$conn->autocommit(False);
try
{
if($videoID > 0)
{
$sql = "SELECT name FROM Persons WHERE id={$id}";
//Debugging
//echo $sql . "<br>";
$persons = mysqli_query($conn, $sql);
if(mysqli_connect_errno($conn))
{
$querySuccess = False;
}
if(isset($persons ) && (count($persons ) > 0))
{
//Loop through every scene
$personData = $persons ->fetch_array(MYSQLI_ASSOC);
}
else
{
return null;
}
}
else
{
$querySuccess = False;
}
}
catch(Exception $e)
{
$querySuccess = False;
}
if(!$querySuccess)
{
//Rollback
$conn->rollback();
die("Transaction failed");
}
else
{
//Commit
$conn->commit();
}
//Close the connection
DBClose($conn);
return json_encode($personData );
}
"Internal server error" means the server crashed somewhere but for security reasons the client only get that 500 error. Check the server's error log file, there should be the real origin of the error (some real error, file and line number). You should start there.
Does the PHP script that uses AJAX have permissions to read the other PHP Script?

AngularJS posting data to a php mysql insert

I'm writing a webapp which successfully allows me to login to Facebook (I'm using Phonegap and the Phonegap Facebook plugin). I then want to store the logged in users name and ID. To start with as a simple test I wanted to get the following controller to run collect the ID, display it in the xcode console to confirm it was there and then send it to the php code below to then store in a mysql table. I can't seem to get it working and I think it's possibly the format of my data in the {}'s within the $http.post but it's a bit beyond my current knowledge to figure this one out. Any ideas?
function FacebookCtrl($scope) {
FB.api('/me', function(response) {
var fbid=response.id;
console.log('Testing, ' + fbid + '.');
$http.post('http://somedomain.co.uk/php/users.php', {uid: fbid})
console.log('Complete');
});
}
The php code at the receiving end is:
<?php
$data = file_get_contents("php://input");
$objData = json_decode($data);
$uid = $objData->uid;
try {
include 'database.php';
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO Userdata (oauth_uid) VALUES (:userid)');
$stmt->execute(array(
':userid' => $uid,
));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
The same php code works with another one of my controllers however the difference is that the other controller captures the data passed from a form so the http.post looks like this:
$http.post('http://somedomain.co.uk/php/submitdata.php', {Position1: $scope.position1}
And the code in the php that captures this data is:
$Position1 = $objData->Position1->Name;
As the code all works on another controller, I'm assuming that the issue is with how I'm formatting the data I'm passing between the {}'s?
Try to define success \ error callbacks
$http.post("http://somedomain.co.uk/php/users.php", {uid: fbid})
.success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
What will it say then?

Categories